@mnmal-ai/substrate-nl 1.0.0-beta.7 → 1.0.0-beta.9

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.
package/README.md CHANGED
@@ -5,9 +5,16 @@ Natural-language ask surface. A deterministic parser reads a question against a
5
5
  ## Contract
6
6
 
7
7
  - `POST /substrate/v1/nl` with `{ namespace, question, project?, type?, asOf? }` returns one of `rows`, `recall`, `clarify` or `refuse`, plus a `trail` of how it got there. Send `accept: application/vnd.substrate.frames+json` for the same as a stream of length-prefixed JSON frames, each `{ event, data }` (`parsed`, `judging`, `judged`, then the outcome, then `done`; a failure mid-stream is an `error` event). Otherwise it is one JSON body. `+pack` is refused `406 not_acceptable`.
8
- - `asOf` is "now" for relative dates ("yesterday", "last week") and for the year of a month-day ("on Oct 23"): an ISO-8601 date-time with an offset, such as `2026-10-02T12:00:00-05:00`. Day boundaries are in its offset. Anything else is `400 invalid_params`. Without it the server clock is used. The `parsed` event's `asOf` says which clock the question was read against.
9
- - Aggregates: `average|avg|mean <field>`, `total|sum [of] <field>`, `min|minimum|max|maximum <field>`, each over the seed type with every filter, value and time range the question also names. The field must be a seed number field (min and max also take a date field). An unknown field, a wrong kind or a field on a walked type is dropped with a reason, and the answer is `unknown`. `highest|lowest <field>` is an aggregate only when `of` or `for` follows the field, a type is named after the field, and no type is named before the superlative ("the highest price of items"). Otherwise it orders ("items with the highest price", "items with the highest price for last week"). A recency or limit word inside a count or an aggregate ("the last sale", "the first 3 items") is dropped as a filter, so the answer is `unknown`. So is an aggregate inside a "how many" question. The outcome is `rows` with `answer: 'aggregate'`, the engine's `data`, and `aggregate: { fn, field, value }`. A store that answers no walks, or a seed under a row policy, refuses the frame: `aggregate` is then absent and `errors` says why. Unlike a count, there is no paged fallback.
10
- - Grouping an aggregate: `by|per day|hour` groups by the type's time field, truncated to the day or hour through `groupBy` and `dateTrunc` (the `timeField` ruling; without one the grouping is dropped with a reason, since `createdAt` is row metadata and cannot sit inside an expression). `by|per <field>` groups by a seed enum or yes/no field, as one aggregate per value (at most 20) plus one for rows with no value. That last group is keyed `null` and is left out when its value is null. Either one gives `aggregate: { fn, field, by, groups: [{ key, value }], truncated? }`. `week`, `month` and `year` buckets, and grouping by any other field, are dropped with a reason, and the ungrouped value still answers.
8
+ - `asOf` is "now" for relative dates ("yesterday", "last week"), for the year of a month-day ("on Oct 23") and for a month with no year ("in march"): an ISO-8601 date-time with an offset, such as `2026-10-02T12:00:00-05:00`, in years 1000 to 9998. Day boundaries are in its offset. Anything else is `400 invalid_params`. Without it the server clock is used. The `parsed` event's `asOf` says which clock the question was read against.
9
+ - Years and months: `in|during 2025` is that whole year. `this year` and `last year` are calendar years, while `last N years` is rolling. `in|during <month>` is the most recent such month that has begun, and `in <month> <year>` or `in <year> <month>` is that month. `since|after|before|until|between|from` take a year or a month as an operand ("since 2024", "before march 2025"). In `between <month> and <month> <year>` a first month with no year takes the second's year, or the year before when it comes later in the calendar, so "between november and february 2026" is 2025-11 to 2026-03. A second month with no year always takes the first's year, and a window that ends before it starts is not read ("between november 2025 and february"). `on` refuses a year or a month. A year is a four-digit number from 1900 to 2199. Any other number there is not a year, so the phrase is not a date, the number stays unread and the answer is `unknown` ("items between 1000 and 2000"). A rolling window too long for a date is not read, and is never an error. A whole month or year after a lead word that is also a stored value, alone or inside a multi-word value of up to 4 words ("todos in may" when `may` is a value, "todos in may release" when `may release` is), is held and dropped with a reason, so the answer is `unknown`.
10
+ - shortId: a number is a shortId after `#`, after an id word (`shortid`, `id`, `number`, `short id`), or right after a singular type word when that type's first mention is singular ("todo 1752", "todo 5 and todo 7", but not "todos and todo 5"). A number after a plural type word or any other word is not an id. A number nothing claimed leaves the reading partial, so the answer is `unknown`. A judge cannot pick away any leftover with a digit in it ("2025", "q3", "fy2025") as noise. Beside an id, a leftover entry that contains a number does the same, while leftover words stay commentary.
11
+ - Aggregates: `average|avg|mean <field>`, `total|sum [of] <field>`, `min|minimum|max|maximum <field>`, each over the seed type with every filter, value and time range the question also names. The field must be a seed number or integer (`int16`, `int32`, `int64`) field (min and max also take a date field). An unknown field, a wrong kind or a field on a walked type is dropped with a reason, and the answer is `unknown`. `highest|lowest <field>` is an aggregate only when `of` or `for` follows the field, a type is named after the field, and no type is named before the superlative ("the highest price of items"). Otherwise it orders ("items with the highest price", "items with the highest price for last week"). A recency or limit word inside a count or an aggregate ("the last sale", "the first 3 items") is dropped as a filter, so the answer is `unknown`. So is an aggregate inside a "how many" question. The outcome is `rows` with `answer: 'aggregate'`, the engine's `data`, and `aggregate: { fn, field, value }`. A `sum` over an integer field, and a `min` or `max` of an `int64` field, is an exact int64, so its `value` (and each group's) is a decimal string on the JSON wire. An `avg` is a number. A store that answers no walks, or a seed under a row policy, refuses the frame: `aggregate` is then absent and `errors` says why. Unlike a plain count, there is no paged fallback. A count per unit runs as an aggregate, so it has none either.
12
+ - Grouping an aggregate or a count: `by|per hour|day|week|month|year` groups by the type's time field (the `timeField` ruling, else `createdAt`; "per month by due date" names a date field of the type instead, by its words or a unique prefix of its name, followed by at most one of `date`, `time`, `day` or `timestamp`, so "by due date" names `dueAt` as well as `dueDate`), truncated through `groupBy` and `dateTrunc`. Labels are the hour `2026-10-20T09`, the day `2026-10-20`, the week's Monday `2026-10-19`, the month `2026-10` and the year `2026`. A count per unit answers `aggregate: { fn: 'count', field: '*', by, groups }`. A unit wins over a field group in the same question: "average price of items by condition per month" groups by month and leaves "condition" unread, so the parse is partial and `ask` answers `unknown`. `by|per <field>` groups by a seed enum or yes/no field, as one aggregate per value (at most 20) plus one for rows with no value. That last group is keyed `null` and is left out when its value is null. Either one gives `aggregate: { fn, field, by, groups: [{ key, value }], truncated? }`. Grouping by any other field is dropped with a reason, and the ungrouped value still answers. The adjectives `hourly|daily|weekly|monthly|yearly|annual|annually` also name a unit:
13
+ - Immediately before or after the aggregate word of a claimed aggregate, an adjective is the unit, even when it is also a pack value.
14
+ - Anywhere else, an adjective that no value claimed is the unit only in a question with a claimed aggregate or "how many" ("how many sales weekly").
15
+ - A field name, or a field phrase, of the asked types (and the types their crossRefs reach) wins over the unit reading ("annual fee"), including right after the aggregate word.
16
+ - A pack value of the namespace claims an adjective only when no aggregate word, claimed or not, is beside it. Beside an aggregate word with no field ("monthly total of subscriptions", "average daily sales") it is neither a value nor a unit, and the answer is `unknown`.
17
+ - An adjective immediately before the aggregate word that is not read as its unit is held and dropped with a reason, and the answer is `unknown`. After the aggregate word, an adjective that names a field is read as the field.
11
18
  - Ordering across one hop: `top|bottom [N] <type> by [pick] <field>` and `<type> with the highest|lowest <field>` may name a number field one crossRef hop away, as `<other type> <field>` ("top 10 items by supplier rating"), a `fieldPhrases` ruling, or a field name only one other type has. The seed's rows are ordered by an `_agg` over that hop, through `select: { <name>: '_agg.<name>' }` and `orderBy: [{ <name>: dir }]`, and each row carries the value under `_agg.<name>`. A hop out to one row reads its value. A direction word right after `by` (`lowest|smallest|least` or `highest|largest|most`) sets the direction, for a seed field too ("top 10 items by lowest price" is ascending). A hop in from many picks one value: `latest|current|most recent` after `by` picks the latest, else the phrase ruling's `pick`, else `max` for a descending order and `min` for an ascending one. Any other pick word after `by` (`cheapest`, or `latest` on a field with one value per row) drops the ordering with a reason. When the field is named as `<type> <field>` and a time range is asked, that type stays a competing reading. The evidence and the plan name it, for example `max(Item.price) per supplier`. Rows with no neighbour sort last. Two or more hops, a field on several types, an unknown field and a non-number field are dropped with a reason.
12
19
  - `GET /substrate/v1/nl/pack/<ns>` returns the namespace pack (types, fields, values, rulings) with an `etag`; send `if-none-match` for a `304`.
13
20
  - NL is read-only: a mutation-shaped question is `refuse`, never executed.
@@ -1 +1 @@
1
- {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/ask/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EAGf,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,cAAc,EAAc,MAAM,cAAc,CAAC;AAC/D,OAAO,EA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yCD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,SAAS,GAAG,UAAU,EAAE,CA2B9F;AAiQD,wBAAuB,MAAM,CAC3B,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,gBAAgB,EACtB,IAAI,EAAE,OAAO,GACZ,cAAc,CAAC,OAAO,CAAC,CAmJzB"}
@@ -233,11 +233,15 @@ const WEEKDAYS = [
233
233
  ];
234
234
  /** An ISO-8601 date-time with an offset: the only accepted `asOf`. */
235
235
  const AS_OF = /^(\d{4})-(\d{2})-(\d{2})T[\d:.]+(Z|[+-]\d{2}:\d{2})$/;
236
- /** True when `asOf` is an ISO-8601 date-time with an offset naming a real instant. */
236
+ /** A year from 1000 to 9998, so every window's end is still a four-digit year. */
237
+ const YEAR = /^(?!9999)[1-9]\d{3}$/;
238
+ /** A year a question names, 1900 to 2199. Any other four-digit number is not read as a year. */
239
+ const CALENDAR_YEAR = /^(?:19|2[01])\d{2}$/;
240
+ /** True when `asOf` is an ISO-8601 date-time with an offset naming a real instant in a `YEAR`. */
237
241
  function validAsOf(asOf) {
238
242
  if (typeof asOf !== "string") return false;
239
243
  const m = AS_OF.exec(asOf);
240
- if (m === null || !Number.isFinite(Date.parse(asOf))) return false;
244
+ if (m === null || !YEAR.test(m[1]) || !Number.isFinite(Date.parse(asOf))) return false;
241
245
  const [y, mo, d] = [
242
246
  Number(m[1]),
243
247
  Number(m[2]),
@@ -248,10 +252,22 @@ function validAsOf(asOf) {
248
252
  /**
249
253
  * The range a time phrase names, relative to `asOf` and in its offset:
250
254
  * today, yesterday, this/last week (weeks start Monday), this/last month,
251
- * rolling "past <unit>" and "last N <units>", "since <weekday>"; and explicit
252
- * dates (see `explicitRange`). Null when the phrase is not a time phrase.
255
+ * this/last year (calendar years), rolling "past <unit>" and "last N <units>",
256
+ * "since <weekday>", any of these after "during" or "during the" (as after the glue
257
+ * words "in the"); and explicit dates (see `explicitRange`). Null when the phrase is
258
+ * not a time phrase, or when a bound falls outside years 1000 to 9998.
253
259
  */
254
260
  function rangeFor(phrase, asOf) {
261
+ const r = windowOf(phrase, asOf);
262
+ return r !== null && supported(r.gte) && supported(r.lt) ? r : null;
263
+ }
264
+ /** True when a bound is a four-digit date from 1000-01-01 to 9999-01-01, the end of a `YEAR`. */
265
+ function supported(bound) {
266
+ const date = bound?.slice(0, 10);
267
+ return date === void 0 || /^\d{4}-/.test(date) && date >= "1000-01-01" && date <= "9999-01-01";
268
+ }
269
+ /** The range `rangeFor` reads, before its bounds are checked. */
270
+ function windowOf(phrase, asOf) {
255
271
  const m = AS_OF.exec(asOf);
256
272
  if (m === null) throw new Error(`asOf must be ISO-8601 with an offset: ${asOf}`);
257
273
  const [, y, mo, d, offset] = m;
@@ -288,6 +304,14 @@ function rangeFor(phrase, asOf) {
288
304
  gte: at(lastMonth),
289
305
  lt: at(monthStart)
290
306
  };
307
+ case "this year": return {
308
+ gte: at(Date.UTC(Number(y), 0, 1)),
309
+ lt: at(Date.UTC(Number(y) + 1, 0, 1))
310
+ };
311
+ case "last year": return {
312
+ gte: at(Date.UTC(Number(y) - 1, 0, 1)),
313
+ lt: at(Date.UTC(Number(y), 0, 1))
314
+ };
291
315
  }
292
316
  const rolling = /^(?:past|last) (\d+ )?(day|week|month|year)s?$/.exec(phrase);
293
317
  if (rolling !== null && (rolling[1] !== void 0 || phrase.startsWith("past"))) {
@@ -298,6 +322,7 @@ function rangeFor(phrase, asOf) {
298
322
  if (unit === "week") back.setUTCDate(back.getUTCDate() - 7 * n);
299
323
  if (unit === "month") back.setUTCMonth(back.getUTCMonth() - n);
300
324
  if (unit === "year") back.setUTCFullYear(back.getUTCFullYear() - n);
325
+ if (Number.isNaN(back.getTime())) return null;
301
326
  return {
302
327
  gte: at(back.getTime()),
303
328
  lt: at(today + day)
@@ -309,13 +334,15 @@ function rangeFor(phrase, asOf) {
309
334
  gte: at(today - (weekday - target + 7) % 7 * day),
310
335
  lt: at(today + day)
311
336
  };
312
- const lead = /^(since|after|before|until) (.+)$/.exec(phrase);
337
+ const lead = /^(since|after|before|until|during the|during) (.+)$/.exec(phrase);
313
338
  const named = lead === null ? null : rangeFor(lead[2], asOf);
314
339
  if (named?.gte !== void 0 && named.lt !== void 0) switch (lead?.[1]) {
315
340
  case "since": return { gte: named.gte };
316
341
  case "after": return { gte: named.lt };
317
342
  case "before": return { lt: named.gte };
318
343
  case "until": return { lt: named.lt };
344
+ case "during":
345
+ case "during the": return named;
319
346
  }
320
347
  return explicitRange(phrase, today, at, offset);
321
348
  }
@@ -334,19 +361,69 @@ const MONTHS = [
334
361
  "december"
335
362
  ];
336
363
  const DAY_MS = 864e5;
364
+ /** A day of the month, with an optional ordinal: "5", "5th". */
365
+ const DAY_OF_MONTH = /^(\d{1,2})(?:st|nd|rd|th)?$/;
366
+ /** A month name's number (full, three-letter, or "sept"), or 0. */
367
+ function monthNumber(w) {
368
+ return MONTHS.findIndex((m) => w === m || w.length === 3 && m.startsWith(w)) + 1 || (w === "sept" ? 9 : 0);
369
+ }
370
+ /**
371
+ * Where a time phrase `rangeFor` accepted names a whole year or month: the positions of
372
+ * the words of each such operand, as "may" in "in may", "june", "august" and "2025" in
373
+ * "between june and august 2025"; none in "on may 5 2025" (a day) or "last 2000 days".
374
+ */
375
+ function unitsAt(phrase) {
376
+ const words = phrase.split(" ");
377
+ const head = words[0] ?? "";
378
+ if (![
379
+ "in",
380
+ "during",
381
+ "since",
382
+ "after",
383
+ "before",
384
+ "until",
385
+ "from",
386
+ "between"
387
+ ].includes(head)) return [];
388
+ const sep = head === "from" ? "to" : head === "between" ? "and" : void 0;
389
+ const out = [];
390
+ for (let start = 1, i = 1; i <= words.length; i++) {
391
+ if (i < words.length && words[i] !== sep) continue;
392
+ const operand = words.slice(start, i);
393
+ if (operand.length <= 2 && operand.every((w) => CALENDAR_YEAR.test(w) || monthNumber(w) > 0)) for (let j = start; j < i; j++) out.push(j);
394
+ start = i + 1;
395
+ }
396
+ return out;
397
+ }
337
398
  /**
338
- * Explicit dates, always after a lead word: "on D" (that day), "from D to D" and
339
- * "between D and D" (inclusive of the last day), "since D" / "after D" (from
340
- * D / the day after), "before D" / "until D" (before D / through D). A date
341
- * is ISO `YYYY-MM-DD`, an ISO date-time (an exact instant), or a month name
342
- * (full, three-letter, or "sept") with a day, optional ordinal and optional year, in
343
- * either order. A month-day without a year is the most recent one not after
344
- * `today`. An invalid date is not a date.
399
+ * Explicit dates, always after a lead word: "on D" (that day), "in Y" / "during Y"
400
+ * (that year or month), "from D to D" and "between D and D" (inclusive of the last
401
+ * day), "since D" / "after D" (from the start of D / from its end: the next day,
402
+ * month or year), "before D" / "until D" (before D starts / through its end). A
403
+ * year is a `CALENDAR_YEAR` and covers its calendar year; a month name, alone or with a
404
+ * year in either order, covers that month (alone, the most recent one that has
405
+ * begun). In "between M and M Y" a yearless first month takes the second's year,
406
+ * or the year before when it comes later in the year ("between november and
407
+ * february 2026"); a yearless second month takes the first's year. A range that
408
+ * ends before it starts is not read. A date is ISO `YYYY-MM-DD`, an ISO date-time (an exact instant),
409
+ * or a month name (full, three-letter, or "sept") with a day, optional ordinal and
410
+ * optional year, in either order. A month-day without a year is the most recent one
411
+ * not after `today`. An invalid date is not a date.
345
412
  */
346
413
  function explicitRange(phrase, today, at, offset) {
347
414
  const operand = (words) => {
348
415
  if (words.length === 1) {
349
416
  const w = words[0];
417
+ if (CALENDAR_YEAR.test(w)) return {
418
+ start: at(Date.UTC(Number(w), 0, 1)),
419
+ end: at(Date.UTC(Number(w) + 1, 0, 1)),
420
+ unit: "year"
421
+ };
422
+ const mo = monthNumber(w);
423
+ if (mo > 0) {
424
+ const thisYear = new Date(today).getUTCFullYear();
425
+ return monthOf(Date.UTC(thisYear, mo - 1, 1) > today ? thisYear - 1 : thisYear, mo);
426
+ }
350
427
  const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(w);
351
428
  if (iso !== null) return dayOf(Number(iso[1]), Number(iso[2]), Number(iso[3]));
352
429
  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);
@@ -359,11 +436,12 @@ function explicitRange(phrase, today, at, offset) {
359
436
  }
360
437
  if (words.length !== 2 && words.length !== 3) return null;
361
438
  const [a = "", b = "", year] = words;
362
- const month = (w) => MONTHS.findIndex((m) => w === m || w.length === 3 && m.startsWith(w)) + 1 || (w === "sept" ? 9 : 0);
363
- const dom = (w) => /^(\d{1,2})(?:st|nd|rd|th)?$/.exec(w)?.[1];
364
- const [mo, d] = month(a) > 0 ? [month(a), dom(b)] : [month(b), dom(a)];
439
+ if (CALENDAR_YEAR.test(b) && monthNumber(a) > 0 && year === void 0) return monthOf(Number(b), monthNumber(a));
440
+ if (CALENDAR_YEAR.test(a) && monthNumber(b) > 0 && year === void 0) return monthOf(Number(a), monthNumber(b));
441
+ const dom = (w) => DAY_OF_MONTH.exec(w)?.[1];
442
+ const [mo, d] = monthNumber(a) > 0 ? [monthNumber(a), dom(b)] : [monthNumber(b), dom(a)];
365
443
  if (mo === 0 || d === void 0) return null;
366
- if (year !== void 0) return /^\d{4}$/.test(year) ? dayOf(Number(year), mo, Number(d)) : null;
444
+ if (year !== void 0) return CALENDAR_YEAR.test(year) ? dayOf(Number(year), mo, Number(d)) : null;
367
445
  for (let y = new Date(today).getUTCFullYear(), n = 0; n < 8; y--, n++) {
368
446
  const t = Date.UTC(y, mo - 1, Number(d));
369
447
  if (t <= today && valid(y, mo, Number(d))) return {
@@ -373,7 +451,13 @@ function explicitRange(phrase, today, at, offset) {
373
451
  }
374
452
  return null;
375
453
  };
454
+ const monthOf = (y, mo) => ({
455
+ start: at(Date.UTC(y, mo - 1, 1)),
456
+ end: at(Date.UTC(y, mo, 1)),
457
+ unit: "month"
458
+ });
376
459
  const valid = (y, mo, d) => {
460
+ if (!YEAR.test(String(y))) return false;
377
461
  const t = new Date(Date.UTC(y, mo - 1, d));
378
462
  return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d;
379
463
  };
@@ -390,8 +474,15 @@ function explicitRange(phrase, today, at, offset) {
390
474
  const sep = head === "from" ? "to" : "and";
391
475
  const i = rest.indexOf(sep);
392
476
  if (i < 0) return null;
393
- const x = operand(rest.slice(0, i));
394
- const y = operand(rest.slice(i + 1));
477
+ const xw = rest.slice(0, i);
478
+ const yw = rest.slice(i + 1);
479
+ const yearOf = (ws) => ws.length === 2 ? ws.find((w) => CALENDAR_YEAR.test(w)) : void 0;
480
+ const monthIn = (ws) => Math.max(...ws.map(monthNumber));
481
+ const bare = (ws) => ws.length === 1 && monthNumber(ws[0]) > 0;
482
+ const xYear = bare(xw) ? yearOf(yw) : void 0;
483
+ const before = xYear !== void 0 && monthIn(xw) > monthIn(yw) ? 1 : 0;
484
+ const x = operand(xYear === void 0 ? xw : [...xw, String(Number(xYear) - before)]);
485
+ const y = operand(bare(yw) && yearOf(xw) ? [...yw, yearOf(xw)] : yw);
395
486
  if (x === null || y === null || Date.parse(y.end) <= Date.parse(x.start)) return null;
396
487
  return {
397
488
  gte: x.start,
@@ -401,7 +492,12 @@ function explicitRange(phrase, today, at, offset) {
401
492
  const o = operand(rest);
402
493
  if (o === null) return null;
403
494
  switch (head) {
404
- case "on": return o.start === o.end ? null : {
495
+ case "on": return o.start === o.end || o.unit !== void 0 ? null : {
496
+ gte: o.start,
497
+ lt: o.end
498
+ };
499
+ case "in":
500
+ case "during": return o.unit === void 0 ? null : {
405
501
  gte: o.start,
406
502
  lt: o.end
407
503
  };
@@ -1171,6 +1267,12 @@ const CLOSED = [
1171
1267
  "resolved"
1172
1268
  ];
1173
1269
  const HISTORY_WORDS = new Set("archived archive history historical ever previously past trend trends over-time all-time total".split(" "));
1270
+ /** Words before a history word that only say "include it": "including archived". */
1271
+ const INCLUDE_WORDS = /* @__PURE__ */ new Set([
1272
+ "including",
1273
+ "include",
1274
+ "plus"
1275
+ ]);
1174
1276
  /** Connectives a composed reading cannot honour; dropped while composing walks. */
1175
1277
  const CONNECTIVES = /* @__PURE__ */ new Set([
1176
1278
  "or",
@@ -1275,17 +1377,26 @@ function parseQuestion(question, pack, ctx) {
1275
1377
  });
1276
1378
  const walkClaims = claimWalkParts(tokens, rulings, GLUE);
1277
1379
  const mentioned = /* @__PURE__ */ new Map();
1380
+ /** Every singular type phrase, by position: a number after one may be an id. */
1381
+ const singularAt = [];
1278
1382
  for (const entry of buildTypeIndex(pack, rulings)) {
1279
1383
  const n = entry.phrase.split(" ").length;
1280
1384
  for (let i = 0; i + n <= tokens.length; i++) {
1281
1385
  const slice = tokens.slice(i, i + n);
1282
1386
  if (slice.some((t) => t.used) || slice.map((t) => t.text).join(" ") !== entry.phrase) continue;
1283
1387
  for (const t of slice) t.used = true;
1284
- for (const type of entry.types) mentioned.set(type, {
1285
- span: entry.phrase,
1286
- plural: entry.plural,
1287
- at: mentioned.get(type)?.at ?? [i, i + n - 1]
1388
+ if (!entry.plural) singularAt.push({
1389
+ types: entry.types,
1390
+ at: [i, i + n - 1]
1288
1391
  });
1392
+ for (const type of entry.types) {
1393
+ const prior = mentioned.get(type);
1394
+ if (prior === void 0 || i < prior.at[0]) mentioned.set(type, {
1395
+ span: entry.phrase,
1396
+ plural: entry.plural,
1397
+ at: [i, i + n - 1]
1398
+ });
1399
+ }
1289
1400
  }
1290
1401
  }
1291
1402
  for (const [type, m] of mentioned) evidence.push({
@@ -1293,13 +1404,24 @@ function parseQuestion(question, pack, ctx) {
1293
1404
  role: "type",
1294
1405
  detail: type
1295
1406
  });
1296
- const time = claimTime(tokens, ctx.asOf);
1407
+ const claimed = claimTime(tokens, ctx.asOf);
1408
+ const heldValue = claimed === null ? void 0 : unitsAt(claimed.span).map((i) => valueAround(tokens, claimed.at[0] + i, claimed.at, pack)).find((v) => v !== void 0);
1409
+ const time = heldValue === void 0 ? claimed : null;
1410
+ const heldTime = claimed === null || heldValue === void 0 ? null : {
1411
+ span: claimed.span,
1412
+ reason: `"${heldValue}" could be a time or a stored value; neither is assumed`,
1413
+ kind: "filter"
1414
+ };
1297
1415
  if (time !== null) evidence.push({
1298
1416
  span: time.span,
1299
1417
  role: "time",
1300
1418
  detail: `${time.range.gte ?? ""} .. ${time.range.lt ?? ""}`.trim()
1301
1419
  });
1302
- const aggregate = claimAggregate(tokens, walkClaims, pack, rulings, [...mentioned.values()].map((m) => m.at[0]));
1420
+ const names = {
1421
+ types: askedTypes(pack, ctx.forceType !== void 0 ? [ctx.forceType] : [...mentioned.keys()]),
1422
+ rulings
1423
+ };
1424
+ const aggregate = claimAggregate(tokens, walkClaims, pack, names, [...mentioned.values()].map((m) => m.at[0]));
1303
1425
  const fieldOrder = claimFieldOrder(tokens, walkClaims, pack, rulings, mentioned);
1304
1426
  const fieldType = fieldOrder?.type;
1305
1427
  if (fieldType !== void 0 && time === null && mentioned.size > 1) {
@@ -1307,6 +1429,7 @@ function parseQuestion(question, pack, ctx) {
1307
1429
  const e = evidence.findIndex((x) => x.role === "type" && x.detail === fieldType);
1308
1430
  if (e >= 0) evidence.splice(e, 1);
1309
1431
  }
1432
+ const followsSingularType = (at) => singularAt.some((s) => at >= s.at[0] && at <= s.at[1] && s.types.some((t) => mentioned.get(t)?.plural === false));
1310
1433
  const ids = [];
1311
1434
  let bareNumber = false;
1312
1435
  tokens.forEach((t, i) => {
@@ -1332,7 +1455,7 @@ function parseQuestion(question, pack, ctx) {
1332
1455
  role: "id",
1333
1456
  detail: "shortId"
1334
1457
  });
1335
- } else if (prev?.used === true && mentioned.size > 0) {
1458
+ } else if (followsSingularType(i - 1)) {
1336
1459
  ids.push(Number(t.text));
1337
1460
  t.used = true;
1338
1461
  evidence.push({
@@ -1345,6 +1468,7 @@ function parseQuestion(question, pack, ctx) {
1345
1468
  });
1346
1469
  let order = null;
1347
1470
  let count = false;
1471
+ let countUnit = null;
1348
1472
  let allProjects = false;
1349
1473
  let historyWord = false;
1350
1474
  const singularMention = [...mentioned.values()].some((m) => !m.plural);
@@ -1372,6 +1496,7 @@ function parseQuestion(question, pack, ctx) {
1372
1496
  count = true;
1373
1497
  t.used = true;
1374
1498
  next.used = true;
1499
+ countUnit = claimUnit(tokens, i + 2);
1375
1500
  evidence.push({
1376
1501
  span: "how many",
1377
1502
  role: "count",
@@ -1392,6 +1517,10 @@ function parseQuestion(question, pack, ctx) {
1392
1517
  } else if (HISTORY_WORDS.has(t.text)) {
1393
1518
  historyWord = true;
1394
1519
  t.used = true;
1520
+ const prev = tokens[i - 1];
1521
+ if (prev !== void 0 && !prev.used && INCLUDE_WORDS.has(prev.text)) prev.used = true;
1522
+ const after = tokens[i + 2];
1523
+ if (next?.text === "or" && after?.text === "not" && !next.used && !after.used) next.used = after.used = true;
1395
1524
  evidence.push({
1396
1525
  span: t.text,
1397
1526
  role: "history",
@@ -1472,6 +1601,7 @@ function parseQuestion(question, pack, ctx) {
1472
1601
  claimNgrams(tokens, 4, (key, at) => {
1473
1602
  if (at.length === 1 && GLUE.has(key)) return false;
1474
1603
  if (at.length === 1 && CLOSE_VERBS.has(key)) return false;
1604
+ if (at.length === 1 && own(UNIT_ADJECTIVES, key) !== void 0 && at.some((k) => besideAggregate(tokens, k))) return false;
1475
1605
  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;
1476
1606
  if (found === null) return false;
1477
1607
  values.push({
@@ -1481,6 +1611,11 @@ function parseQuestion(question, pack, ctx) {
1481
1611
  });
1482
1612
  return true;
1483
1613
  });
1614
+ if ((aggregate !== null || count) && aggregate?.group === void 0 && countUnit === null) {
1615
+ const unit = claimUnit(tokens, 0, names, true);
1616
+ if (aggregate !== null && unit !== null) aggregate.group = unit;
1617
+ else countUnit = unit;
1618
+ }
1484
1619
  const closeVerb = words.some((w) => CLOSE_VERBS.has(w));
1485
1620
  const updateVerb = words.some((w) => UPDATE_VERBS.has(w));
1486
1621
  for (const t of tokens) if (CLOSE_VERBS.has(t.text) || UPDATE_VERBS.has(t.text)) t.used = true;
@@ -1562,10 +1697,16 @@ function parseQuestion(question, pack, ctx) {
1562
1697
  values,
1563
1698
  clauses,
1564
1699
  time: composed === void 0 || composed.timeOnSeed ? time : null,
1700
+ heldTime,
1565
1701
  order,
1566
1702
  fieldOrder: fieldOrder ?? composed?.seedOrder ?? null,
1567
1703
  plural: mentioned.get(type)?.plural ?? false,
1568
1704
  count,
1705
+ countUnit: countUnit ?? (aggregate?.group?.unit !== void 0 ? {
1706
+ span: aggregate.group.span,
1707
+ unit: aggregate.group.unit,
1708
+ end: aggregate.group.end ?? tokens.length
1709
+ } : null),
1569
1710
  aggregate,
1570
1711
  allProjects,
1571
1712
  historyWord,
@@ -1601,7 +1742,8 @@ function parseQuestion(question, pack, ctx) {
1601
1742
  residual: only.residual,
1602
1743
  reason: `dropped: ${only.dropped.map((d) => `"${d.span}" (${d.reason})`).join("; ")}`
1603
1744
  };
1604
- if (only.residual.length > 0 && ids.length === 0) return {
1745
+ const numbered = (w) => w.split(" ").some((x) => /^\$?\d+(?:\.\d+)?[%×]?$/.test(x));
1746
+ if (only.residual.some((w) => ids.length === 0 || numbered(w))) return {
1605
1747
  status: "partial",
1606
1748
  candidates,
1607
1749
  residual: only.residual,
@@ -1684,6 +1826,12 @@ function assemble(type, a) {
1684
1826
  reason: `${a.count ? "counting" : "aggregating"} over the latest N rows is not supported`,
1685
1827
  kind: "filter"
1686
1828
  }] : [],
1829
+ ...a.heldTime !== null ? [a.heldTime] : [],
1830
+ ...a.aggregate?.held !== void 0 ? [{
1831
+ span: a.aggregate.held,
1832
+ reason: `beside "${a.aggregate.word}" it could be the unit or part of another reading; neither is assumed`,
1833
+ kind: "filter"
1834
+ }] : [],
1687
1835
  ...a.count && a.aggregate !== null ? [{
1688
1836
  span: a.aggregate.span,
1689
1837
  reason: "an aggregate does not apply to a count",
@@ -1760,7 +1908,14 @@ function assemble(type, a) {
1760
1908
  if (a.author !== null) where.push({ createdById: { startsWith: a.author } });
1761
1909
  const orderExclude = a.fieldOrder?.phrase?.entry.exclude;
1762
1910
  if (sortBy !== null && sortBy.hop === void 0 && orderExclude !== void 0) where.push({ NOT: orderExclude });
1763
- const agg = aggClaim === null ? null : aggregateOn(aggClaim, type, pack, rulings);
1911
+ const unitClaim = a.count ? a.countUnit : aggClaim?.group?.unit !== void 0 ? {
1912
+ ...aggClaim.group,
1913
+ end: aggClaim.group.end ?? tokens.length
1914
+ } : null;
1915
+ const bucket = unitClaim === null ? null : claimDateField(tokens, unitClaim.end, fields, rulings);
1916
+ const bucketField = bucket?.name ?? null;
1917
+ const agg = aggClaim === null ? null : aggregateOn(aggClaim, type, pack, rulings, bucketField ?? void 0);
1918
+ if (agg !== null && agg.fn === void 0) for (const t of bucket?.taken ?? []) t.used = false;
1764
1919
  if (agg !== null) {
1765
1920
  dropped.push(...agg.dropped);
1766
1921
  ev.push(...agg.evidence);
@@ -1899,11 +2054,23 @@ function assemble(type, a) {
1899
2054
  delete params.select;
1900
2055
  delete params.orderBy;
1901
2056
  }
2057
+ const countBy = a.count && a.countUnit !== null ? a.countUnit : null;
2058
+ const timeField = bucketField ?? own(rulings.timeField, type) ?? "createdAt";
2059
+ if (countBy !== null) {
2060
+ params.aggregate = { value: { count: true } };
2061
+ params.groupBy = { bucket: { dateTrunc: [{ lit: countBy.unit }, timeField] } };
2062
+ ev.push({
2063
+ span: countBy.span,
2064
+ role: "field",
2065
+ detail: `bucket ${timeField} by ${countBy.unit}`
2066
+ });
2067
+ }
1902
2068
  if (agg?.fn !== void 0 && agg.field !== void 0) {
1903
2069
  params.aggregate = { value: { [agg.fn]: agg.field } };
1904
2070
  if (agg.dateGroup !== void 0) params.groupBy = { bucket: { dateTrunc: [{ lit: agg.dateGroup.by }, agg.dateGroup.field] } };
1905
2071
  }
1906
- 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";
2072
+ const strict = a.count || aggClaim !== null || order !== null || sortBy !== null || a.ids.length === 1 || a.composed?.strict === true;
2073
+ const answer = aggClaim !== null || countBy !== 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";
1907
2074
  return {
1908
2075
  type,
1909
2076
  frame: { [`${pack.namespace}/${type}`]: {
@@ -1915,18 +2082,30 @@ function assemble(type, a) {
1915
2082
  residual: contentWords(tokens),
1916
2083
  plan,
1917
2084
  dropped,
1918
- ...agg?.fn !== void 0 && agg.field !== void 0 ? { aggregate: {
2085
+ ...countBy !== null ? { aggregate: {
2086
+ fn: "count",
2087
+ field: "*"
2088
+ } } : agg?.fn !== void 0 && agg.field !== void 0 ? { aggregate: {
1919
2089
  fn: agg.fn,
1920
2090
  field: agg.field,
1921
2091
  ...agg.group !== void 0 ? { group: agg.group } : {}
1922
2092
  } } : {},
1923
- strict: a.count || aggClaim !== null || order !== null || sortBy !== null || a.ids.length === 1 || a.composed?.strict === true
2093
+ strict
1924
2094
  };
1925
2095
  }
1926
2096
  /** A field named by words on one type: one of its field phrases, else its name or an alias. */
1927
2097
  function fieldByWords(words, fields, rulings) {
1928
2098
  return Object.entries(fields).find(([, f]) => f.phrases.includes(words))?.[0] ?? (words.includes(" ") ? null : resolveField(words, fields, rulings));
1929
2099
  }
2100
+ /** True when `words` name a field somewhere and every field they name is a yes/no field. */
2101
+ function onlyBoolean(words, pack, rulings) {
2102
+ if (words === void 0) return false;
2103
+ const named = Object.values(pack.types).flatMap((t) => {
2104
+ const n = fieldByWords(words, t.fields, rulings);
2105
+ return n === null ? [] : [t.fields[n]];
2106
+ });
2107
+ return named.length > 0 && named.every((f) => f?.valueType === "boolean");
2108
+ }
1930
2109
  /**
1931
2110
  * The field named at `i`: a field phrase claim, else the longest run of up to
1932
2111
  * three free words naming a field on some type, else (unless `numeric`) one
@@ -1943,10 +2122,7 @@ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1943
2122
  const slice = tokens.slice(i, i + n);
1944
2123
  if (slice.length < n || slice.some((t) => t.used)) continue;
1945
2124
  const w = slice.map((t) => t.text).join(" ");
1946
- if (Object.values(pack.types).some((t) => {
1947
- const name = fieldByWords(w, t.fields, rulings);
1948
- return name !== null && (!numeric || t.fields[name]?.valueType === "number");
1949
- })) return {
2125
+ if (namesField(w, Object.values(pack.types), rulings, numeric)) return {
1950
2126
  words: w,
1951
2127
  span: w,
1952
2128
  end: i + n - 1
@@ -1959,6 +2135,17 @@ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1959
2135
  end: i
1960
2136
  } : null;
1961
2137
  }
2138
+ /** Integer kinds sum, average and order like `number`. */
2139
+ const isNumeric = (valueType) => valueType === "number" || valueType === "int16" || valueType === "int32" || valueType === "int64";
2140
+ /** A field kind with its article: "an int32", "a date". */
2141
+ const aKind = (kind) => `${/^[aeiou]/.test(kind ?? "") ? "an" : "a"} ${kind}`;
2142
+ /** True when `words` name a field on one of `types` (a number field, with `numeric`). */
2143
+ function namesField(words, types, rulings, numeric = false) {
2144
+ return types.some((t) => {
2145
+ const name = fieldByWords(words, t.fields, rulings);
2146
+ return name !== null && (!numeric || isNumeric(t.fields[name]?.valueType));
2147
+ });
2148
+ }
1962
2149
  /** Marks tokens `from`..`f.end` used; a field phrase named here is not walked to. */
1963
2150
  function takeField(tokens, walkClaims, from, f) {
1964
2151
  for (let k = from; k <= f.end; k++) tokens[k].used = true;
@@ -2122,20 +2309,125 @@ const DIRECTION_WORDS = {
2122
2309
  };
2123
2310
  /** A field grouping runs one frame per value: more than this is dropped. */
2124
2311
  const MAX_GROUPS = 20;
2125
- const BUCKET_WORDS = /* @__PURE__ */ new Set([
2312
+ const TIME_UNITS = [
2126
2313
  "hour",
2127
2314
  "day",
2128
2315
  "week",
2129
2316
  "month",
2130
2317
  "year"
2318
+ ];
2319
+ /** Adjectives that name a unit: "monthly total", "how many sales weekly". */
2320
+ const UNIT_ADJECTIVES = {
2321
+ hourly: "hour",
2322
+ daily: "day",
2323
+ weekly: "week",
2324
+ monthly: "month",
2325
+ yearly: "year",
2326
+ annual: "year",
2327
+ annually: "year"
2328
+ };
2329
+ /** Whether the token just before or after token `k` is an aggregate word, claimed or not. */
2330
+ function besideAggregate(tokens, k) {
2331
+ return [k - 1, k + 1].some((j) => own(AGGREGATE_WORDS, tokens[j]?.text ?? "") !== void 0);
2332
+ }
2333
+ /** The asked types and the types their crossRefs reach; every type when none is asked. */
2334
+ function askedTypes(pack, asked) {
2335
+ const seeds = asked.flatMap((t) => own(pack.types, t) ?? []);
2336
+ if (seeds.length === 0) return Object.values(pack.types);
2337
+ const reached = seeds.flatMap((t) => Object.values(t.fields).flatMap((f) => f.target?.namespace === pack.namespace ? own(pack.types, f.target.type) ?? [] : []));
2338
+ return [.../* @__PURE__ */ new Set([...seeds, ...reached])];
2339
+ }
2340
+ /**
2341
+ * The unit a free adjective at `k` names, unless it alone or with the next one or
2342
+ * two words, claimed or not, names a field of `names.types` ("annual fee", "annual total").
2343
+ */
2344
+ function adjectiveAt(tokens, k, names) {
2345
+ const t = tokens[k];
2346
+ const unit = t === void 0 || t.used ? void 0 : own(UNIT_ADJECTIVES, t.text);
2347
+ if (unit === void 0) return void 0;
2348
+ const words = tokens.slice(k, k + 3).map((x) => x.text);
2349
+ return [
2350
+ 1,
2351
+ 2,
2352
+ 3
2353
+ ].some((n) => namesField(words.slice(0, n).join(" "), names.types, names.rulings)) ? void 0 : unit;
2354
+ }
2355
+ /** Words that may follow a named date field without naming anything else ("by due date"). */
2356
+ const GENERIC_DATE_WORDS = /* @__PURE__ */ new Set([
2357
+ "date",
2358
+ "time",
2359
+ "day",
2360
+ "timestamp"
2131
2361
  ]);
2132
2362
  /**
2363
+ * Claims "by <date field>" right after a unit phrase ending at token `end` ("per month by due
2364
+ * date"): the longest run of up to three free words naming a date field, or a lone word that
2365
+ * starts exactly one date field's phrase ("due"), then one free generic date word the field's
2366
+ * own words do not hold ("due date" on `dueAt`). Anything else stays unread.
2367
+ */
2368
+ function claimDateField(tokens, end, fields, rulings) {
2369
+ const by = tokens[end + 1];
2370
+ if (by === void 0 || by.used || by.text !== "by") return null;
2371
+ const dates = Object.values(fields).filter((f) => f.valueType === "date");
2372
+ for (let n = 3; n >= 1; n--) {
2373
+ const slice = tokens.slice(end + 2, end + 2 + n);
2374
+ if (slice.length < n || slice.some((t) => t.used)) continue;
2375
+ const words = slice.map((t) => t.text).join(" ");
2376
+ const named = fieldByWords(words, fields, rulings);
2377
+ const starts = dates.filter((f) => f.phrases.some((p) => p.startsWith(`${words} `)));
2378
+ const name = named ?? (starts.length === 1 ? starts[0]?.name ?? null : null);
2379
+ const f = name === null ? void 0 : fields[name];
2380
+ if (name === null || f?.valueType !== "date") continue;
2381
+ const taken = [by, ...slice];
2382
+ const next = tokens[end + 2 + n];
2383
+ if (next !== void 0 && !next.used && GENERIC_DATE_WORDS.has(next.text) && !f.phrases.some((p) => p.split(" ").includes(next.text))) taken.push(next);
2384
+ for (const t of taken) t.used = true;
2385
+ return {
2386
+ name,
2387
+ taken
2388
+ };
2389
+ }
2390
+ return null;
2391
+ }
2392
+ /**
2393
+ * Claims "by|per <unit>" from token `from` on, skipping used tokens and "<author verb> by";
2394
+ * with `adjectives`, a unit adjective too, whichever comes first. With `awayFromAggregate`,
2395
+ * an adjective next to an aggregate word is skipped: that word did not claim it as its unit.
2396
+ */
2397
+ function claimUnit(tokens, from, adjectives, awayFromAggregate = false) {
2398
+ for (let k = from; k < tokens.length; k++) {
2399
+ const by = tokens[k];
2400
+ const adjective = adjectives === void 0 || awayFromAggregate && besideAggregate(tokens, k) ? void 0 : adjectiveAt(tokens, k, adjectives);
2401
+ if (adjective !== void 0) {
2402
+ by.used = true;
2403
+ return {
2404
+ span: by.text,
2405
+ unit: adjective,
2406
+ end: k
2407
+ };
2408
+ }
2409
+ if (by.used || by.text !== "by" && by.text !== "per") continue;
2410
+ if (AUTHOR_VERBS.has(tokens[k - 1]?.text ?? "")) continue;
2411
+ const next = tokens[k + 1];
2412
+ const unit = next === void 0 || next.used ? void 0 : TIME_UNITS.find((u) => u === next.text);
2413
+ if (next === void 0 || unit === void 0) continue;
2414
+ by.used = next.used = true;
2415
+ return {
2416
+ span: `${by.text} ${next.text}`,
2417
+ unit,
2418
+ end: k + 1
2419
+ };
2420
+ }
2421
+ return null;
2422
+ }
2423
+ /**
2133
2424
  * Claims one aggregate. "highest|lowest <field>" is a value only when "of" or
2134
2425
  * "for" follows the field and a type is named after it, none before the
2135
2426
  * superlative ("the highest price of items"); otherwise it stays an ordering
2136
2427
  * ("items with the highest price", "… highest price for last week").
2137
2428
  */
2138
- function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2429
+ function claimAggregate(tokens, walkClaims, pack, names, mentions) {
2430
+ const { rulings } = names;
2139
2431
  const ofFollows = (end) => VALUE_OF.has(tokens[end + 1]?.text ?? "");
2140
2432
  const valueAt = (start, end) => ofFollows(end) && mentions.some((m) => m > end) && !mentions.some((m) => m < start);
2141
2433
  for (let i = 0; i < tokens.length; i++) {
@@ -2153,11 +2445,14 @@ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2153
2445
  end: pick.phrase.at[1]
2154
2446
  };
2155
2447
  } else {
2156
- let j = i + 1;
2448
+ let j = adjectiveAt(tokens, i + 1, names) === void 0 ? i + 1 : i + 2;
2157
2449
  while (!(tokens[j]?.used ?? true) && (tokens[j]?.text === "of" || tokens[j]?.text === "the")) j++;
2158
2450
  f = fieldAt(tokens, walkClaims, pack, rulings, j, false);
2159
2451
  if (f === null || VALUE_SUPERLATIVES.has(t.text) && !valueAt(i, f.end)) continue;
2452
+ if (onlyBoolean(f.words, pack, rulings)) continue;
2160
2453
  }
2454
+ const beside = [i + 1, i - 1].find((k) => adjectiveAt(tokens, k, names) !== void 0);
2455
+ const besideUnit = beside === void 0 ? null : claimUnit(tokens, beside, names);
2161
2456
  takeField(tokens, walkClaims, i, f);
2162
2457
  const claim = {
2163
2458
  span: tokens.slice(i, f.end + 1).map((x) => x.text).join(" "),
@@ -2165,19 +2460,20 @@ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2165
2460
  fn,
2166
2461
  field: fieldRef(f)
2167
2462
  };
2463
+ const prev = tokens[i - 1];
2464
+ if (prev !== void 0 && !prev.used && own(UNIT_ADJECTIVES, prev.text) !== void 0) {
2465
+ prev.used = true;
2466
+ claim.held = prev.text;
2467
+ }
2468
+ const byUnit = besideUnit ?? claimUnit(tokens, 0);
2469
+ if (byUnit !== null) {
2470
+ claim.group = byUnit;
2471
+ return claim;
2472
+ }
2168
2473
  for (let k = 0; k < tokens.length; k++) {
2169
2474
  const by = tokens[k];
2170
2475
  if (by.used || by.text !== "by" && by.text !== "per") continue;
2171
2476
  if (AUTHOR_VERBS.has(tokens[k - 1]?.text ?? "")) continue;
2172
- const next = tokens[k + 1];
2173
- if (next !== void 0 && !next.used && BUCKET_WORDS.has(next.text)) {
2174
- by.used = next.used = true;
2175
- claim.group = {
2176
- span: `${by.text} ${next.text}`,
2177
- unit: next.text
2178
- };
2179
- break;
2180
- }
2181
2477
  const g = fieldAt(tokens, walkClaims, pack, rulings, k + 1, false);
2182
2478
  if (g === null) continue;
2183
2479
  takeField(tokens, walkClaims, k, g);
@@ -2215,13 +2511,14 @@ function seedField(o, type, pack, rulings, doing) {
2215
2511
  };
2216
2512
  }
2217
2513
  /** An aggregate claim read on `type`: its function and field, or drops saying why not. */
2218
- function aggregateOn(c, type, pack, rulings) {
2514
+ function aggregateOn(c, type, pack, rulings, bucketField) {
2219
2515
  const r = seedField({
2220
2516
  span: c.span,
2221
2517
  ...c.field
2222
2518
  }, type, pack, rulings, "aggregating");
2223
2519
  const wants = c.fn === "min" || c.fn === "max" ? ["number", "date"] : ["number"];
2224
- 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`;
2520
+ const accepts = (vt) => isNumeric(vt) || wants.length > 1 && vt === "date";
2521
+ const reason = "reason" in r ? r.reason : (r.f.kind === "scalar" || r.f.kind === "metadata") && accepts(r.f.valueType) ? null : `${c.word} needs a ${wants.join(" or ")} field; ${r.name} is ${aKind(r.f.valueType ?? r.f.kind)} field`;
2225
2522
  if (reason !== null || "reason" in r) return {
2226
2523
  dropped: [{
2227
2524
  span: c.span,
@@ -2253,8 +2550,7 @@ function aggregateOn(c, type, pack, rulings) {
2253
2550
  return out;
2254
2551
  };
2255
2552
  if (g.unit !== void 0) {
2256
- if (g.unit !== "day" && g.unit !== "hour") return drop("only day and hour groupings are supported");
2257
- const field = own(rulings.timeField, type) ?? "createdAt";
2553
+ const field = bucketField ?? own(rulings.timeField, type) ?? "createdAt";
2258
2554
  out.dateGroup = {
2259
2555
  field,
2260
2556
  by: g.unit
@@ -2293,7 +2589,7 @@ function orderField(o, type, pack, rulings) {
2293
2589
  if ("reason" in r) return r;
2294
2590
  const { name, f } = r;
2295
2591
  if (o.pick !== void 0) return { reason: pickReason(o.pick, `${type}.${name}`, type) };
2296
- 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` };
2592
+ if (!((f.kind === "scalar" || f.kind === "metadata") && (isNumeric(f.valueType) || f.valueType === "date" && o.numeric !== true))) return { reason: o.numeric === true ? `"most" needs a number field; ${name} is ${aKind(f.valueType ?? f.kind)} field` : `${name} is ${aKind(f.valueType ?? f.kind)} field; only number and date fields order` };
2297
2593
  return { field: name };
2298
2594
  }
2299
2595
  /** Why a pick word cannot order: it is not a direction, or there is one value per seed row. */
@@ -2342,12 +2638,12 @@ function hopOrder(o, seed, to, pack, rulings) {
2342
2638
  if (path.length > 1) return { reason: `ordering across ${path.length} hops is not supported; one hop only` };
2343
2639
  const f = own(pack.types, to.type)?.fields[to.field];
2344
2640
  const qualified = `${to.type}.${to.field}`;
2345
- 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` };
2641
+ 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 ${aKind(f?.valueType ?? f?.kind)} field` };
2346
2642
  const h = path[0];
2347
2643
  if (o.pick !== void 0 && (h.dir === "out" || o.pick.kind !== "latest")) return { reason: pickReason(o.pick, qualified, seed) };
2348
2644
  const cap = to.field.charAt(0).toUpperCase() + to.field.slice(1);
2349
- const exclude = o.phrase?.entry.exclude;
2350
- const where = exclude !== void 0 ? { where: { NOT: exclude } } : {};
2645
+ const excludes = [o.phrase?.entry.exclude, own(rulings.typeExcludes, to.type)].flatMap((x) => x === void 0 ? [] : [{ NOT: x }]);
2646
+ const where = excludes.length === 0 ? {} : { where: excludes.length === 1 ? excludes[0] : { AND: excludes } };
2351
2647
  if (h.dir === "out") return { hop: {
2352
2648
  name: `${to.type.charAt(0).toLowerCase()}${to.type.slice(1)}${cap}`,
2353
2649
  agg: {
@@ -2386,6 +2682,11 @@ function coerce(raw, f) {
2386
2682
  const n = Number(raw);
2387
2683
  return Number.isFinite(n) ? n : void 0;
2388
2684
  }
2685
+ if (isNumeric(f.valueType)) {
2686
+ if (!/^-?\d+$/.test(raw)) return void 0;
2687
+ const n = Number(raw);
2688
+ return Number.isSafeInteger(n) ? n : BigInt(raw).toString();
2689
+ }
2389
2690
  if (f.valueType === "boolean") return raw === "true" ? true : raw === "false" ? false : void 0;
2390
2691
  return raw;
2391
2692
  }
@@ -2415,18 +2716,36 @@ function creditFieldWords(tokens, field) {
2415
2716
  }
2416
2717
  return hit;
2417
2718
  }
2719
+ /** Unexplained words, and a lone unread number, which no reading may lose. */
2418
2720
  function contentWords(tokens) {
2419
2721
  const free = (t) => t !== void 0 && !t.used && !GLUE.has(t.text);
2420
2722
  const num = (t) => free(t) && /^\d+$/.test(t.text);
2723
+ const word = (t) => free(t) && !num(t);
2421
2724
  const out = [];
2422
2725
  tokens.forEach((t, i) => {
2423
- if (!free(t) || num(t)) return;
2726
+ if (!free(t)) return;
2727
+ if (num(t)) {
2728
+ if (!word(tokens[i - 1]) && !word(tokens[i + 1])) out.push(t.text);
2729
+ return;
2730
+ }
2424
2731
  const before = num(tokens[i - 1]) ? `${tokens[i - 1]?.text} ` : "";
2425
2732
  const after = num(tokens[i + 1]) && !(free(tokens[i + 2]) && !num(tokens[i + 2])) ? ` ${tokens[i + 1]?.text}` : "";
2426
2733
  out.push(`${before}${t.text}${after}`);
2427
2734
  });
2428
2735
  return out;
2429
2736
  }
2737
+ /**
2738
+ * A pack value of up to four words, as the value pass reads, that takes in token `k` and
2739
+ * whose other words are free or in `span`: "may", "june 2025", "may release".
2740
+ */
2741
+ function valueAround(tokens, k, span, pack) {
2742
+ for (let n = 4; n >= 1; n--) for (let i = Math.max(0, k - n + 1); i <= k && i + n <= tokens.length; i++) {
2743
+ const slice = tokens.slice(i, i + n);
2744
+ if (slice.some((t, j) => t.used && (i + j < span[0] || i + j > span[1]))) continue;
2745
+ const key = slice.map((t) => t.text).join(" ");
2746
+ if (own(pack.values, key) !== void 0) return key;
2747
+ }
2748
+ }
2430
2749
  /** Claims the longest n-grams (up to `max` words) for which `accept` returns true. */
2431
2750
  function claimNgrams(tokens, max, accept) {
2432
2751
  for (let n = max; n >= 1; n--) for (let i = 0; i + n <= tokens.length; i++) {
@@ -2715,8 +3034,9 @@ async function parseWithJudge(question, pack, ctx, judge, opts = {}) {
2715
3034
  trail
2716
3035
  };
2717
3036
  }
2718
- if (chosen.strict && chosen.residual.length > 0) {
2719
- const reason = `unexplained under a strict reading: ${chosen.residual.join(", ")}`;
3037
+ const digits = chosen.residual.filter((w) => /\d/.test(w));
3038
+ if (chosen.strict && chosen.residual.length > 0 || digits.length > 0) {
3039
+ const reason = chosen.strict ? `unexplained under a strict reading: ${chosen.residual.join(", ")}` : `a digit is never noise: ${digits.join(", ")}`;
2720
3040
  return {
2721
3041
  status: "escalated",
2722
3042
  result: {
@@ -2894,6 +3214,14 @@ async function rows(c, source, question, http, deps, handoff, leftovers = []) {
2894
3214
  plan: mergePlan(c.plan, env._diagnostics?.[key]?.plan)
2895
3215
  };
2896
3216
  }
3217
+ /** Characters of the engine's canonical instant that name a group of each unit. */
3218
+ const LABEL_LENGTH = {
3219
+ hour: 13,
3220
+ day: 10,
3221
+ week: 10,
3222
+ month: 7,
3223
+ year: 4
3224
+ };
2897
3225
  /**
2898
3226
  * An aggregate answer: the engine's one frame, or, grouped by a field the
2899
3227
  * engine cannot group, one frame per value of it.
@@ -2932,8 +3260,9 @@ async function aggregate(c, frame, key, source, http, deps, dropped, handoff) {
2932
3260
  }
2933
3261
  const trunc = params.groupBy?.bucket?.dateTrunc;
2934
3262
  const by = group?.field ?? trunc?.[0].lit;
2935
- const short = (k) => typeof k === "string" && trunc !== void 0 ? k.slice(0, trunc[0].lit === "day" ? 10 : 13) : k;
3263
+ const short = (k) => typeof k === "string" && trunc !== void 0 ? k.slice(0, LABEL_LENGTH[trunc[0].lit]) : k;
2936
3264
  const rows = data?.groups;
3265
+ const wire = (v) => typeof v === "bigint" ? v.toString() : v;
2937
3266
  const result = rows === void 0 ? void 0 : {
2938
3267
  fn,
2939
3268
  field,
@@ -2941,9 +3270,9 @@ async function aggregate(c, frame, key, source, http, deps, dropped, handoff) {
2941
3270
  by,
2942
3271
  groups: rows.filter((g) => trunc === void 0 || g.bucket !== null).map((g) => ({
2943
3272
  key: short(g.bucket ?? g.key),
2944
- value: g.value
3273
+ value: wire(g.value)
2945
3274
  }))
2946
- } : { value: rows[0]?.value ?? null },
3275
+ } : { value: wire(rows[0]?.value ?? null) },
2947
3276
  ...data?.truncated === true ? { truncated: true } : {}
2948
3277
  };
2949
3278
  return {
@@ -2987,6 +3316,15 @@ async function countRest(frame, key, seen, first, http, deps) {
2987
3316
  }
2988
3317
  return count;
2989
3318
  }
3319
+ /** The row fields `ask` returns per recall hit: enough to name and pick a row. */
3320
+ const HIT_ROW = {
3321
+ shortId: true,
3322
+ name: true,
3323
+ title: true,
3324
+ topic: true,
3325
+ synopsis: true,
3326
+ description: true
3327
+ };
2990
3328
  async function recall(query, ns, type, http, deps) {
2991
3329
  const frame = { "recall/Hit": {
2992
3330
  params: {
@@ -3000,7 +3338,7 @@ async function recall(query, ns, type, http, deps) {
3000
3338
  namespace: true,
3001
3339
  type: true,
3002
3340
  score: true,
3003
- row: true
3341
+ row: HIT_ROW
3004
3342
  }
3005
3343
  } };
3006
3344
  const env = await deps.engine.query(frame, http);
@@ -3510,7 +3848,9 @@ var PackService = class {
3510
3848
  params: cursor !== void 0 ? { cursor } : {},
3511
3849
  fields: Object.fromEntries(fields.map((f) => [f, true]))
3512
3850
  } }, req);
3851
+ if (req.signal?.aborted === true) throw new Error(`pack build for '${ns}' was cancelled`);
3513
3852
  const rows = env.data?.[frameKey];
3853
+ if (rows === void 0 && transientRefusal(env.errors)) throw new Error(`pack build: reading ${frameKey} failed: ${JSON.stringify(env.errors ?? [])}`);
3514
3854
  const page = env._pagination?.[frameKey];
3515
3855
  return {
3516
3856
  rows: Array.isArray(rows) ? rows : [],
@@ -3539,6 +3879,21 @@ var PackService = class {
3539
3879
  }
3540
3880
  };
3541
3881
  /**
3882
+ * Refusals that may not recur on the next build. Any other refusal (a policy
3883
+ * denial, a type that only streams) is lasting, and leaves the type's values out.
3884
+ */
3885
+ const TRANSIENT = /* @__PURE__ */ new Set([
3886
+ "aborted",
3887
+ "query_timeout",
3888
+ "store_busy"
3889
+ ]);
3890
+ function transientRefusal(errors) {
3891
+ return (errors ?? []).some((e) => {
3892
+ const code = e?.code;
3893
+ return typeof code === "string" && TRANSIENT.has(code);
3894
+ });
3895
+ }
3896
+ /**
3542
3897
  * The Identity canonicalised, less `expiresAt`: a custom row policy may key on
3543
3898
  * any claim (a tenant, say), so no other subset is safe to share a cached pack
3544
3899
  * across, while a token's expiry changes with every refresh.
package/dist/bootstrap.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as bootstrap, t as NlBootstrapConfigSchema } from "./bootstrap-BVBxKpxA.js";
1
+ import { n as bootstrap, t as NlBootstrapConfigSchema } from "./bootstrap-CNk9iqtw.js";
2
2
 
3
3
  export { NlBootstrapConfigSchema, bootstrap, bootstrap as default };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as askHandler, c as profileNamespace, d as runAsk, f as parseWithJudge, g as readRulings, h as mergeRulings, i as createNlPlugin, l as buildNamespacePack, m as NamespaceRulingsSchema, n as bootstrap, o as packHandler, p as parseQuestion, r as CONTRACT_VERSION, s as PackService, t as NlBootstrapConfigSchema, u as OllamaJudge } from "./bootstrap-BVBxKpxA.js";
1
+ import { a as askHandler, c as profileNamespace, d as runAsk, f as parseWithJudge, g as readRulings, h as mergeRulings, i as createNlPlugin, l as buildNamespacePack, m as NamespaceRulingsSchema, n as bootstrap, o as packHandler, p as parseQuestion, r as CONTRACT_VERSION, s as PackService, t as NlBootstrapConfigSchema, u as OllamaJudge } from "./bootstrap-CNk9iqtw.js";
2
2
  import { complete } from "./complete.js";
3
3
 
4
4
  export { CONTRACT_VERSION, NamespaceRulingsSchema, NlBootstrapConfigSchema, OllamaJudge, PackService, askHandler, bootstrap, buildNamespacePack, complete, createNlPlugin, mergeRulings, packHandler, parseQuestion, parseWithJudge, profileNamespace, readRulings, runAsk };
@@ -1 +1 @@
1
- {"version":3,"file":"judge.d.ts","sourceRoot":"","sources":["../../src/judge/judge.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEzF,OAA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C,CA4BzD;CAuCF"}
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/pack/service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAU,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACtF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAKnD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,MAAM,MAAM,UAAU,GAAG,YAAY,CAAC;AAEtC,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,cAAc,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IAC3C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9B;AAQD;;;;;GAKG;AACH,qBAAa,WAAW;;IAMtB,YAAY,IAAI,EAAE,kBAAkB,EAEnC;IAEK,GAAG,CACP,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,gBAAgB,GACpB,OAAO,CAAC;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC,CA4BzD;CA+CF"}
@@ -48,7 +48,7 @@ export interface Candidate {
48
48
  * engine cannot express, run as one aggregate per value.
49
49
  */
50
50
  aggregate?: {
51
- fn: AggregateFn;
51
+ fn: AggregateFn | 'count';
52
52
  field: string;
53
53
  group?: {
54
54
  field: string;
@@ -68,5 +68,8 @@ export interface ParseResult {
68
68
  }
69
69
  export declare function parseQuestion(question: string, pack: NamespacePack, ctx: ParseContext): ParseResult;
70
70
  type AggregateFn = 'avg' | 'sum' | 'min' | 'max';
71
+ declare const TIME_UNITS: readonly ['hour', 'day', 'week', 'month', 'year'];
72
+ /** The units a date group can truncate to. */
73
+ export type TimeUnit = (typeof TIME_UNITS)[number];
71
74
  export {};
72
75
  //# sourceMappingURL=parse.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../../src/parse/parse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAE9F,OAAO,KAAK,EAAE,gBAAgB,EAAc,MAAM,oBAAoB,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAa,MAAM,kBAAkB,CAAC;AAsBjE,MAAM,WAAW,YAAY;IAC3B,qEAAqE;IACrE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sDAAsD;IACtD,IAAI,EAAE,MAAM,CAAC;IACb,kCAAkC;IAClC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAC3B,wFAAwF;IACxF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,QAAQ,GAAG,UAAU,CAAC;AAElC,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,8FAA8F;IAC9F,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC,CAAC;IAC7F,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,QAAQ,EAAE,CAAC;IACrB,qDAAqD;IACrD,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,qGAAqG;IACrG,IAAI,EAAE,UAAU,EAAE,CAAC;IACnB,yFAAyF;IACzF,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB;;;OAG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M,EAChB,IAAI,EAAE,aAAa,EACnB,GAAG,EAAE,YAAY,GAChB,WAAW,CAgcb;AAivBD,KAAK,WAAW,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;AA4BjD,QAAA,MAAM,UAAU,YAAI,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAU,CAAC;AACrE,8CAA8C;AAC9C,MAAM,MAAM,QAAQ,GAAG,CAAC,OAAO,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC"}
@@ -9,13 +9,21 @@ export type DateRange = {
9
9
  gte?: never;
10
10
  lt: string;
11
11
  };
12
- /** True when `asOf` is an ISO-8601 date-time with an offset naming a real instant. */
12
+ /** True when `asOf` is an ISO-8601 date-time with an offset naming a real instant in a `YEAR`. */
13
13
  export declare function validAsOf(asOf: unknown): asOf is string;
14
14
  /**
15
15
  * The range a time phrase names, relative to `asOf` and in its offset:
16
16
  * today, yesterday, this/last week (weeks start Monday), this/last month,
17
- * rolling "past <unit>" and "last N <units>", "since <weekday>"; and explicit
18
- * dates (see `explicitRange`). Null when the phrase is not a time phrase.
17
+ * this/last year (calendar years), rolling "past <unit>" and "last N <units>",
18
+ * "since <weekday>", any of these after "during" or "during the" (as after the glue
19
+ * words "in the"); and explicit dates (see `explicitRange`). Null when the phrase is
20
+ * not a time phrase, or when a bound falls outside years 1000 to 9998.
19
21
  */
20
22
  export declare function rangeFor(phrase: string, asOf: string): DateRange | null;
23
+ /**
24
+ * Where a time phrase `rangeFor` accepted names a whole year or month: the positions of
25
+ * the words of each such operand, as "may" in "in may", "june", "august" and "2025" in
26
+ * "between june and august 2025"; none in "on may 5 2025" (a day) or "last 2000 days".
27
+ */
28
+ export declare function unitsAt(phrase: string): number[];
21
29
  //# sourceMappingURL=time.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/parse/time.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,MAAM,MAAM,SAAS,GACjB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,KAAK,CAAA;CAAE,GAC3B;IAAE,GAAG,CAAC,EAAE,KAAK,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAOhC,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,MAAM,CAMvD;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CA8DvE"}
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/parse/time.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,MAAM,MAAM,SAAS,GACjB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,KAAK,CAAA;CAAE,GAC3B;IAAE,GAAG,CAAC,EAAE,KAAK,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAWhC,kGAAkG;AAClG,wBAAgB,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,MAAM,CAMvD;AAED;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAGvE;AA8GD;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAehD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate-nl",
3
- "version": "1.0.0-beta.7",
3
+ "version": "1.0.0-beta.9",
4
4
  "description": "Natural-language questions for Substrate — a deterministic parser with an optional constrained judge, served at POST /substrate/v1/nl and GET /substrate/v1/nl/pack/:ns, plus browser-safe completion.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -37,8 +37,8 @@
37
37
  },
38
38
  "devDependencies": {
39
39
  "@biomejs/biome": "2.6.4",
40
- "@mnmal-ai/substrate": "1.0.0-beta.7",
41
- "@mnmal-ai/substrate-config": "1.0.0-beta.7",
40
+ "@mnmal-ai/substrate": "1.0.0-beta.9",
41
+ "@mnmal-ai/substrate-config": "1.0.0-beta.9",
42
42
  "@types/node": "^26.6.4",
43
43
  "postgres": "4.1.0",
44
44
  "tsdown": "^0.23.0",