@mnmal-ai/substrate-nl 1.0.0-beta.6 → 1.0.0-beta.8

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 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 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`), 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.
@@ -30,7 +37,7 @@ A **kernel-tier plugin**, installed separately: `pnpm add @mnmal-ai/substrate-nl
30
37
  }
31
38
  ```
32
39
 
33
- - `judge` optional: an [Ollama](https://ollama.com) server and model for the constrained judge (`timeoutMs` defaults to 20000). Absent means parser-only: every escalation is an honest hand-off. A slow or down judge hands off within `timeoutMs`.
40
+ - `judge` optional: an [Ollama](https://ollama.com) server and model for the constrained judge (`timeoutMs` defaults to 20000). Absent means parser-only: every escalation is an honest hand-off. A slow or down judge hands off within `timeoutMs`. A hand-off with words the parser could not read answers `unknown` and runs nothing.
34
41
  - `rulings` optional; per-namespace overrides merged over rulings the namespace declares.
35
42
  - `packTtlMs` how long a served pack is reused (default 300000).
36
43
 
@@ -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,EAAE,KAAK,KAAK,EAAqC,MAAM,mBAAmB,CAAC;AAElF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAa,MAAM,aAAa,CAAC;AAElE,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAyCD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,SAAS,GAAG,UAAU,EAAE,CA2B9F;AAgPD,wBAAuB,MAAM,CAC3B,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,gBAAgB,EACtB,IAAI,EAAE,OAAO,GACZ,cAAc,CAAC,OAAO,CAAC,CAmJzB"}
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,EAAE,KAAK,KAAK,EAAqC,MAAM,mBAAmB,CAAC;AAElF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAa,MAAM,aAAa,CAAC;AAElE,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAyCD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,SAAS,GAAG,UAAU,EAAE,CA2B9F;AA+PD,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",
@@ -1181,6 +1283,12 @@ const CONNECTIVES = /* @__PURE__ */ new Set([
1181
1283
  const LATEST = new Set("latest newest recent last".split(" "));
1182
1284
  const OLDEST = new Set("oldest earliest first".split(" "));
1183
1285
  const AUTHOR_VERBS = new Set("raised created written filed authored opened made sent logged".split(" "));
1286
+ /** Words that make the number after them a shortId: "shortId 1752", "id 1752", "number 1752". */
1287
+ const ID_WORDS = /* @__PURE__ */ new Set([
1288
+ "shortid",
1289
+ "id",
1290
+ "number"
1291
+ ]);
1184
1292
  const BUILTIN_FIELD_ALIASES = { author: "createdById" };
1185
1293
  /** `field:value`, `field:[a,b]`, `field:"two words"`; optionally wrapped in quotes. A clock time starts with a digit. */
1186
1294
  const CLAUSE = /(['"]?)\b([A-Za-z][A-Za-z0-9]*):(\[[^\]]*\]|"[^"]*"|[^\s,'"]+)\1/g;
@@ -1269,17 +1377,26 @@ function parseQuestion(question, pack, ctx) {
1269
1377
  });
1270
1378
  const walkClaims = claimWalkParts(tokens, rulings, GLUE);
1271
1379
  const mentioned = /* @__PURE__ */ new Map();
1380
+ /** Every singular type phrase, by position: a number after one may be an id. */
1381
+ const singularAt = [];
1272
1382
  for (const entry of buildTypeIndex(pack, rulings)) {
1273
1383
  const n = entry.phrase.split(" ").length;
1274
1384
  for (let i = 0; i + n <= tokens.length; i++) {
1275
1385
  const slice = tokens.slice(i, i + n);
1276
1386
  if (slice.some((t) => t.used) || slice.map((t) => t.text).join(" ") !== entry.phrase) continue;
1277
1387
  for (const t of slice) t.used = true;
1278
- for (const type of entry.types) mentioned.set(type, {
1279
- span: entry.phrase,
1280
- plural: entry.plural,
1281
- 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]
1282
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
+ }
1283
1400
  }
1284
1401
  }
1285
1402
  for (const [type, m] of mentioned) evidence.push({
@@ -1287,13 +1404,24 @@ function parseQuestion(question, pack, ctx) {
1287
1404
  role: "type",
1288
1405
  detail: type
1289
1406
  });
1290
- 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
+ };
1291
1415
  if (time !== null) evidence.push({
1292
1416
  span: time.span,
1293
1417
  role: "time",
1294
1418
  detail: `${time.range.gte ?? ""} .. ${time.range.lt ?? ""}`.trim()
1295
1419
  });
1296
- 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]));
1297
1425
  const fieldOrder = claimFieldOrder(tokens, walkClaims, pack, rulings, mentioned);
1298
1426
  const fieldType = fieldOrder?.type;
1299
1427
  if (fieldType !== void 0 && time === null && mentioned.size > 1) {
@@ -1301,6 +1429,7 @@ function parseQuestion(question, pack, ctx) {
1301
1429
  const e = evidence.findIndex((x) => x.role === "type" && x.detail === fieldType);
1302
1430
  if (e >= 0) evidence.splice(e, 1);
1303
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));
1304
1433
  const ids = [];
1305
1434
  let bareNumber = false;
1306
1435
  tokens.forEach((t, i) => {
@@ -1314,7 +1443,19 @@ function parseQuestion(question, pack, ctx) {
1314
1443
  detail: "shortId"
1315
1444
  });
1316
1445
  } else if (/^\d+$/.test(t.text)) {
1317
- if (tokens[i - 1]?.used === true && mentioned.size > 0) {
1446
+ const prev = tokens[i - 1];
1447
+ if (prev !== void 0 && !prev.used && ID_WORDS.has(prev.text)) {
1448
+ ids.push(Number(t.text));
1449
+ t.used = true;
1450
+ prev.used = true;
1451
+ const before = tokens[i - 2];
1452
+ if (prev.text === "id" && before?.text === "short" && !before.used) before.used = true;
1453
+ evidence.push({
1454
+ span: `${prev.text} ${t.text}`,
1455
+ role: "id",
1456
+ detail: "shortId"
1457
+ });
1458
+ } else if (followsSingularType(i - 1)) {
1318
1459
  ids.push(Number(t.text));
1319
1460
  t.used = true;
1320
1461
  evidence.push({
@@ -1327,6 +1468,7 @@ function parseQuestion(question, pack, ctx) {
1327
1468
  });
1328
1469
  let order = null;
1329
1470
  let count = false;
1471
+ let countUnit = null;
1330
1472
  let allProjects = false;
1331
1473
  let historyWord = false;
1332
1474
  const singularMention = [...mentioned.values()].some((m) => !m.plural);
@@ -1354,6 +1496,7 @@ function parseQuestion(question, pack, ctx) {
1354
1496
  count = true;
1355
1497
  t.used = true;
1356
1498
  next.used = true;
1499
+ countUnit = claimUnit(tokens, i + 2);
1357
1500
  evidence.push({
1358
1501
  span: "how many",
1359
1502
  role: "count",
@@ -1374,6 +1517,10 @@ function parseQuestion(question, pack, ctx) {
1374
1517
  } else if (HISTORY_WORDS.has(t.text)) {
1375
1518
  historyWord = true;
1376
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;
1377
1524
  evidence.push({
1378
1525
  span: t.text,
1379
1526
  role: "history",
@@ -1454,6 +1601,7 @@ function parseQuestion(question, pack, ctx) {
1454
1601
  claimNgrams(tokens, 4, (key, at) => {
1455
1602
  if (at.length === 1 && GLUE.has(key)) return false;
1456
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;
1457
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;
1458
1606
  if (found === null) return false;
1459
1607
  values.push({
@@ -1463,6 +1611,11 @@ function parseQuestion(question, pack, ctx) {
1463
1611
  });
1464
1612
  return true;
1465
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
+ }
1466
1619
  const closeVerb = words.some((w) => CLOSE_VERBS.has(w));
1467
1620
  const updateVerb = words.some((w) => UPDATE_VERBS.has(w));
1468
1621
  for (const t of tokens) if (CLOSE_VERBS.has(t.text) || UPDATE_VERBS.has(t.text)) t.used = true;
@@ -1544,10 +1697,15 @@ function parseQuestion(question, pack, ctx) {
1544
1697
  values,
1545
1698
  clauses,
1546
1699
  time: composed === void 0 || composed.timeOnSeed ? time : null,
1700
+ heldTime,
1547
1701
  order,
1548
1702
  fieldOrder: fieldOrder ?? composed?.seedOrder ?? null,
1549
1703
  plural: mentioned.get(type)?.plural ?? false,
1550
1704
  count,
1705
+ countUnit: countUnit ?? (aggregate?.group?.unit !== void 0 ? {
1706
+ span: aggregate.group.span,
1707
+ unit: aggregate.group.unit
1708
+ } : null),
1551
1709
  aggregate,
1552
1710
  allProjects,
1553
1711
  historyWord,
@@ -1583,7 +1741,8 @@ function parseQuestion(question, pack, ctx) {
1583
1741
  residual: only.residual,
1584
1742
  reason: `dropped: ${only.dropped.map((d) => `"${d.span}" (${d.reason})`).join("; ")}`
1585
1743
  };
1586
- if (only.residual.length > 0 && ids.length === 0) return {
1744
+ const numbered = (w) => w.split(" ").some((x) => /^\$?\d+(?:\.\d+)?[%×]?$/.test(x));
1745
+ if (only.residual.some((w) => ids.length === 0 || numbered(w))) return {
1587
1746
  status: "partial",
1588
1747
  candidates,
1589
1748
  residual: only.residual,
@@ -1666,6 +1825,12 @@ function assemble(type, a) {
1666
1825
  reason: `${a.count ? "counting" : "aggregating"} over the latest N rows is not supported`,
1667
1826
  kind: "filter"
1668
1827
  }] : [],
1828
+ ...a.heldTime !== null ? [a.heldTime] : [],
1829
+ ...a.aggregate?.held !== void 0 ? [{
1830
+ span: a.aggregate.held,
1831
+ reason: `beside "${a.aggregate.word}" it could be the unit or part of another reading; neither is assumed`,
1832
+ kind: "filter"
1833
+ }] : [],
1669
1834
  ...a.count && a.aggregate !== null ? [{
1670
1835
  span: a.aggregate.span,
1671
1836
  reason: "an aggregate does not apply to a count",
@@ -1881,11 +2046,23 @@ function assemble(type, a) {
1881
2046
  delete params.select;
1882
2047
  delete params.orderBy;
1883
2048
  }
2049
+ const countBy = a.count && a.countUnit !== null ? a.countUnit : null;
2050
+ const timeField = own(rulings.timeField, type) ?? "createdAt";
2051
+ if (countBy !== null) {
2052
+ params.aggregate = { value: { count: true } };
2053
+ params.groupBy = { bucket: { dateTrunc: [{ lit: countBy.unit }, timeField] } };
2054
+ ev.push({
2055
+ span: countBy.span,
2056
+ role: "field",
2057
+ detail: `bucket ${timeField} by ${countBy.unit}`
2058
+ });
2059
+ }
1884
2060
  if (agg?.fn !== void 0 && agg.field !== void 0) {
1885
2061
  params.aggregate = { value: { [agg.fn]: agg.field } };
1886
2062
  if (agg.dateGroup !== void 0) params.groupBy = { bucket: { dateTrunc: [{ lit: agg.dateGroup.by }, agg.dateGroup.field] } };
1887
2063
  }
1888
- 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";
2064
+ const strict = a.count || aggClaim !== null || order !== null || sortBy !== null || a.ids.length === 1 || a.composed?.strict === true;
2065
+ 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";
1889
2066
  return {
1890
2067
  type,
1891
2068
  frame: { [`${pack.namespace}/${type}`]: {
@@ -1897,18 +2074,30 @@ function assemble(type, a) {
1897
2074
  residual: contentWords(tokens),
1898
2075
  plan,
1899
2076
  dropped,
1900
- ...agg?.fn !== void 0 && agg.field !== void 0 ? { aggregate: {
2077
+ ...countBy !== null ? { aggregate: {
2078
+ fn: "count",
2079
+ field: "*"
2080
+ } } : agg?.fn !== void 0 && agg.field !== void 0 ? { aggregate: {
1901
2081
  fn: agg.fn,
1902
2082
  field: agg.field,
1903
2083
  ...agg.group !== void 0 ? { group: agg.group } : {}
1904
2084
  } } : {},
1905
- strict: a.count || aggClaim !== null || order !== null || sortBy !== null || a.ids.length === 1 || a.composed?.strict === true
2085
+ strict
1906
2086
  };
1907
2087
  }
1908
2088
  /** A field named by words on one type: one of its field phrases, else its name or an alias. */
1909
2089
  function fieldByWords(words, fields, rulings) {
1910
2090
  return Object.entries(fields).find(([, f]) => f.phrases.includes(words))?.[0] ?? (words.includes(" ") ? null : resolveField(words, fields, rulings));
1911
2091
  }
2092
+ /** True when `words` name a field somewhere and every field they name is a yes/no field. */
2093
+ function onlyBoolean(words, pack, rulings) {
2094
+ if (words === void 0) return false;
2095
+ const named = Object.values(pack.types).flatMap((t) => {
2096
+ const n = fieldByWords(words, t.fields, rulings);
2097
+ return n === null ? [] : [t.fields[n]];
2098
+ });
2099
+ return named.length > 0 && named.every((f) => f?.valueType === "boolean");
2100
+ }
1912
2101
  /**
1913
2102
  * The field named at `i`: a field phrase claim, else the longest run of up to
1914
2103
  * three free words naming a field on some type, else (unless `numeric`) one
@@ -1925,10 +2114,7 @@ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1925
2114
  const slice = tokens.slice(i, i + n);
1926
2115
  if (slice.length < n || slice.some((t) => t.used)) continue;
1927
2116
  const w = slice.map((t) => t.text).join(" ");
1928
- if (Object.values(pack.types).some((t) => {
1929
- const name = fieldByWords(w, t.fields, rulings);
1930
- return name !== null && (!numeric || t.fields[name]?.valueType === "number");
1931
- })) return {
2117
+ if (namesField(w, Object.values(pack.types), rulings, numeric)) return {
1932
2118
  words: w,
1933
2119
  span: w,
1934
2120
  end: i + n - 1
@@ -1941,6 +2127,13 @@ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1941
2127
  end: i
1942
2128
  } : null;
1943
2129
  }
2130
+ /** True when `words` name a field on one of `types` (a number field, with `numeric`). */
2131
+ function namesField(words, types, rulings, numeric = false) {
2132
+ return types.some((t) => {
2133
+ const name = fieldByWords(words, t.fields, rulings);
2134
+ return name !== null && (!numeric || t.fields[name]?.valueType === "number");
2135
+ });
2136
+ }
1944
2137
  /** Marks tokens `from`..`f.end` used; a field phrase named here is not walked to. */
1945
2138
  function takeField(tokens, walkClaims, from, f) {
1946
2139
  for (let k = from; k <= f.end; k++) tokens[k].used = true;
@@ -2104,20 +2297,86 @@ const DIRECTION_WORDS = {
2104
2297
  };
2105
2298
  /** A field grouping runs one frame per value: more than this is dropped. */
2106
2299
  const MAX_GROUPS = 20;
2107
- const BUCKET_WORDS = /* @__PURE__ */ new Set([
2300
+ const TIME_UNITS = [
2108
2301
  "hour",
2109
2302
  "day",
2110
2303
  "week",
2111
2304
  "month",
2112
2305
  "year"
2113
- ]);
2306
+ ];
2307
+ /** Adjectives that name a unit: "monthly total", "how many sales weekly". */
2308
+ const UNIT_ADJECTIVES = {
2309
+ hourly: "hour",
2310
+ daily: "day",
2311
+ weekly: "week",
2312
+ monthly: "month",
2313
+ yearly: "year",
2314
+ annual: "year",
2315
+ annually: "year"
2316
+ };
2317
+ /** Whether the token just before or after token `k` is an aggregate word, claimed or not. */
2318
+ function besideAggregate(tokens, k) {
2319
+ return [k - 1, k + 1].some((j) => own(AGGREGATE_WORDS, tokens[j]?.text ?? "") !== void 0);
2320
+ }
2321
+ /** The asked types and the types their crossRefs reach; every type when none is asked. */
2322
+ function askedTypes(pack, asked) {
2323
+ const seeds = asked.flatMap((t) => own(pack.types, t) ?? []);
2324
+ if (seeds.length === 0) return Object.values(pack.types);
2325
+ const reached = seeds.flatMap((t) => Object.values(t.fields).flatMap((f) => f.target?.namespace === pack.namespace ? own(pack.types, f.target.type) ?? [] : []));
2326
+ return [.../* @__PURE__ */ new Set([...seeds, ...reached])];
2327
+ }
2328
+ /**
2329
+ * The unit a free adjective at `k` names, unless it alone or with the next one or
2330
+ * two words, claimed or not, names a field of `names.types` ("annual fee", "annual total").
2331
+ */
2332
+ function adjectiveAt(tokens, k, names) {
2333
+ const t = tokens[k];
2334
+ const unit = t === void 0 || t.used ? void 0 : own(UNIT_ADJECTIVES, t.text);
2335
+ if (unit === void 0) return void 0;
2336
+ const words = tokens.slice(k, k + 3).map((x) => x.text);
2337
+ return [
2338
+ 1,
2339
+ 2,
2340
+ 3
2341
+ ].some((n) => namesField(words.slice(0, n).join(" "), names.types, names.rulings)) ? void 0 : unit;
2342
+ }
2343
+ /**
2344
+ * Claims "by|per <unit>" from token `from` on, skipping used tokens and "<author verb> by";
2345
+ * with `adjectives`, a unit adjective too, whichever comes first. With `awayFromAggregate`,
2346
+ * an adjective next to an aggregate word is skipped: that word did not claim it as its unit.
2347
+ */
2348
+ function claimUnit(tokens, from, adjectives, awayFromAggregate = false) {
2349
+ for (let k = from; k < tokens.length; k++) {
2350
+ const by = tokens[k];
2351
+ const adjective = adjectives === void 0 || awayFromAggregate && besideAggregate(tokens, k) ? void 0 : adjectiveAt(tokens, k, adjectives);
2352
+ if (adjective !== void 0) {
2353
+ by.used = true;
2354
+ return {
2355
+ span: by.text,
2356
+ unit: adjective
2357
+ };
2358
+ }
2359
+ if (by.used || by.text !== "by" && by.text !== "per") continue;
2360
+ if (AUTHOR_VERBS.has(tokens[k - 1]?.text ?? "")) continue;
2361
+ const next = tokens[k + 1];
2362
+ const unit = next === void 0 || next.used ? void 0 : TIME_UNITS.find((u) => u === next.text);
2363
+ if (next === void 0 || unit === void 0) continue;
2364
+ by.used = next.used = true;
2365
+ return {
2366
+ span: `${by.text} ${next.text}`,
2367
+ unit
2368
+ };
2369
+ }
2370
+ return null;
2371
+ }
2114
2372
  /**
2115
2373
  * Claims one aggregate. "highest|lowest <field>" is a value only when "of" or
2116
2374
  * "for" follows the field and a type is named after it, none before the
2117
2375
  * superlative ("the highest price of items"); otherwise it stays an ordering
2118
2376
  * ("items with the highest price", "… highest price for last week").
2119
2377
  */
2120
- function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2378
+ function claimAggregate(tokens, walkClaims, pack, names, mentions) {
2379
+ const { rulings } = names;
2121
2380
  const ofFollows = (end) => VALUE_OF.has(tokens[end + 1]?.text ?? "");
2122
2381
  const valueAt = (start, end) => ofFollows(end) && mentions.some((m) => m > end) && !mentions.some((m) => m < start);
2123
2382
  for (let i = 0; i < tokens.length; i++) {
@@ -2135,11 +2394,14 @@ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2135
2394
  end: pick.phrase.at[1]
2136
2395
  };
2137
2396
  } else {
2138
- let j = i + 1;
2397
+ let j = adjectiveAt(tokens, i + 1, names) === void 0 ? i + 1 : i + 2;
2139
2398
  while (!(tokens[j]?.used ?? true) && (tokens[j]?.text === "of" || tokens[j]?.text === "the")) j++;
2140
2399
  f = fieldAt(tokens, walkClaims, pack, rulings, j, false);
2141
2400
  if (f === null || VALUE_SUPERLATIVES.has(t.text) && !valueAt(i, f.end)) continue;
2401
+ if (onlyBoolean(f.words, pack, rulings)) continue;
2142
2402
  }
2403
+ const beside = [i + 1, i - 1].find((k) => adjectiveAt(tokens, k, names) !== void 0);
2404
+ const besideUnit = beside === void 0 ? null : claimUnit(tokens, beside, names);
2143
2405
  takeField(tokens, walkClaims, i, f);
2144
2406
  const claim = {
2145
2407
  span: tokens.slice(i, f.end + 1).map((x) => x.text).join(" "),
@@ -2147,19 +2409,20 @@ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2147
2409
  fn,
2148
2410
  field: fieldRef(f)
2149
2411
  };
2412
+ const prev = tokens[i - 1];
2413
+ if (prev !== void 0 && !prev.used && own(UNIT_ADJECTIVES, prev.text) !== void 0) {
2414
+ prev.used = true;
2415
+ claim.held = prev.text;
2416
+ }
2417
+ const byUnit = besideUnit ?? claimUnit(tokens, 0);
2418
+ if (byUnit !== null) {
2419
+ claim.group = byUnit;
2420
+ return claim;
2421
+ }
2150
2422
  for (let k = 0; k < tokens.length; k++) {
2151
2423
  const by = tokens[k];
2152
2424
  if (by.used || by.text !== "by" && by.text !== "per") continue;
2153
2425
  if (AUTHOR_VERBS.has(tokens[k - 1]?.text ?? "")) continue;
2154
- const next = tokens[k + 1];
2155
- if (next !== void 0 && !next.used && BUCKET_WORDS.has(next.text)) {
2156
- by.used = next.used = true;
2157
- claim.group = {
2158
- span: `${by.text} ${next.text}`,
2159
- unit: next.text
2160
- };
2161
- break;
2162
- }
2163
2426
  const g = fieldAt(tokens, walkClaims, pack, rulings, k + 1, false);
2164
2427
  if (g === null) continue;
2165
2428
  takeField(tokens, walkClaims, k, g);
@@ -2235,7 +2498,6 @@ function aggregateOn(c, type, pack, rulings) {
2235
2498
  return out;
2236
2499
  };
2237
2500
  if (g.unit !== void 0) {
2238
- if (g.unit !== "day" && g.unit !== "hour") return drop("only day and hour groupings are supported");
2239
2501
  const field = own(rulings.timeField, type) ?? "createdAt";
2240
2502
  out.dateGroup = {
2241
2503
  field,
@@ -2397,18 +2659,36 @@ function creditFieldWords(tokens, field) {
2397
2659
  }
2398
2660
  return hit;
2399
2661
  }
2662
+ /** Unexplained words, and a lone unread number, which no reading may lose. */
2400
2663
  function contentWords(tokens) {
2401
2664
  const free = (t) => t !== void 0 && !t.used && !GLUE.has(t.text);
2402
2665
  const num = (t) => free(t) && /^\d+$/.test(t.text);
2666
+ const word = (t) => free(t) && !num(t);
2403
2667
  const out = [];
2404
2668
  tokens.forEach((t, i) => {
2405
- if (!free(t) || num(t)) return;
2669
+ if (!free(t)) return;
2670
+ if (num(t)) {
2671
+ if (!word(tokens[i - 1]) && !word(tokens[i + 1])) out.push(t.text);
2672
+ return;
2673
+ }
2406
2674
  const before = num(tokens[i - 1]) ? `${tokens[i - 1]?.text} ` : "";
2407
2675
  const after = num(tokens[i + 1]) && !(free(tokens[i + 2]) && !num(tokens[i + 2])) ? ` ${tokens[i + 1]?.text}` : "";
2408
2676
  out.push(`${before}${t.text}${after}`);
2409
2677
  });
2410
2678
  return out;
2411
2679
  }
2680
+ /**
2681
+ * A pack value of up to four words, as the value pass reads, that takes in token `k` and
2682
+ * whose other words are free or in `span`: "may", "june 2025", "may release".
2683
+ */
2684
+ function valueAround(tokens, k, span, pack) {
2685
+ for (let n = 4; n >= 1; n--) for (let i = Math.max(0, k - n + 1); i <= k && i + n <= tokens.length; i++) {
2686
+ const slice = tokens.slice(i, i + n);
2687
+ if (slice.some((t, j) => t.used && (i + j < span[0] || i + j > span[1]))) continue;
2688
+ const key = slice.map((t) => t.text).join(" ");
2689
+ if (own(pack.values, key) !== void 0) return key;
2690
+ }
2691
+ }
2412
2692
  /** Claims the longest n-grams (up to `max` words) for which `accept` returns true. */
2413
2693
  function claimNgrams(tokens, max, accept) {
2414
2694
  for (let n = max; n >= 1; n--) for (let i = 0; i + n <= tokens.length; i++) {
@@ -2697,8 +2977,9 @@ async function parseWithJudge(question, pack, ctx, judge, opts = {}) {
2697
2977
  trail
2698
2978
  };
2699
2979
  }
2700
- if (chosen.strict && chosen.residual.length > 0) {
2701
- const reason = `unexplained under a strict reading: ${chosen.residual.join(", ")}`;
2980
+ const digits = chosen.residual.filter((w) => /\d/.test(w));
2981
+ if (chosen.strict && chosen.residual.length > 0 || digits.length > 0) {
2982
+ const reason = chosen.strict ? `unexplained under a strict reading: ${chosen.residual.join(", ")}` : `a digit is never noise: ${digits.join(", ")}`;
2702
2983
  return {
2703
2984
  status: "escalated",
2704
2985
  result: {
@@ -2839,7 +3120,7 @@ function mergePlan(parsed, engine) {
2839
3120
  }
2840
3121
  async function rows(c, source, question, http, deps, handoff, leftovers = []) {
2841
3122
  const dropped = [...c.dropped, ...leftovers];
2842
- if (c.strict && dropped.some((d) => d.kind === "filter")) return {
3123
+ if ((c.strict || source === "handoff") && dropped.some((d) => d.kind === "filter")) return {
2843
3124
  kind: "unknown",
2844
3125
  question,
2845
3126
  dropped,
@@ -2876,6 +3157,14 @@ async function rows(c, source, question, http, deps, handoff, leftovers = []) {
2876
3157
  plan: mergePlan(c.plan, env._diagnostics?.[key]?.plan)
2877
3158
  };
2878
3159
  }
3160
+ /** Characters of the engine's canonical instant that name a group of each unit. */
3161
+ const LABEL_LENGTH = {
3162
+ hour: 13,
3163
+ day: 10,
3164
+ week: 10,
3165
+ month: 7,
3166
+ year: 4
3167
+ };
2879
3168
  /**
2880
3169
  * An aggregate answer: the engine's one frame, or, grouped by a field the
2881
3170
  * engine cannot group, one frame per value of it.
@@ -2914,7 +3203,7 @@ async function aggregate(c, frame, key, source, http, deps, dropped, handoff) {
2914
3203
  }
2915
3204
  const trunc = params.groupBy?.bucket?.dateTrunc;
2916
3205
  const by = group?.field ?? trunc?.[0].lit;
2917
- const short = (k) => typeof k === "string" && trunc !== void 0 ? k.slice(0, trunc[0].lit === "day" ? 10 : 13) : k;
3206
+ const short = (k) => typeof k === "string" && trunc !== void 0 ? k.slice(0, LABEL_LENGTH[trunc[0].lit]) : k;
2918
3207
  const rows = data?.groups;
2919
3208
  const result = rows === void 0 ? void 0 : {
2920
3209
  fn,
@@ -2969,6 +3258,15 @@ async function countRest(frame, key, seen, first, http, deps) {
2969
3258
  }
2970
3259
  return count;
2971
3260
  }
3261
+ /** The row fields `ask` returns per recall hit: enough to name and pick a row. */
3262
+ const HIT_ROW = {
3263
+ shortId: true,
3264
+ name: true,
3265
+ title: true,
3266
+ topic: true,
3267
+ synopsis: true,
3268
+ description: true
3269
+ };
2972
3270
  async function recall(query, ns, type, http, deps) {
2973
3271
  const frame = { "recall/Hit": {
2974
3272
  params: {
@@ -2982,7 +3280,7 @@ async function recall(query, ns, type, http, deps) {
2982
3280
  namespace: true,
2983
3281
  type: true,
2984
3282
  score: true,
2985
- row: true
3283
+ row: HIT_ROW
2986
3284
  }
2987
3285
  } };
2988
3286
  const env = await deps.engine.query(frame, http);
@@ -3492,7 +3790,9 @@ var PackService = class {
3492
3790
  params: cursor !== void 0 ? { cursor } : {},
3493
3791
  fields: Object.fromEntries(fields.map((f) => [f, true]))
3494
3792
  } }, req);
3793
+ if (req.signal?.aborted === true) throw new Error(`pack build for '${ns}' was cancelled`);
3495
3794
  const rows = env.data?.[frameKey];
3795
+ if (rows === void 0 && transientRefusal(env.errors)) throw new Error(`pack build: reading ${frameKey} failed: ${JSON.stringify(env.errors ?? [])}`);
3496
3796
  const page = env._pagination?.[frameKey];
3497
3797
  return {
3498
3798
  rows: Array.isArray(rows) ? rows : [],
@@ -3521,6 +3821,21 @@ var PackService = class {
3521
3821
  }
3522
3822
  };
3523
3823
  /**
3824
+ * Refusals that may not recur on the next build. Any other refusal (a policy
3825
+ * denial, a type that only streams) is lasting, and leaves the type's values out.
3826
+ */
3827
+ const TRANSIENT = /* @__PURE__ */ new Set([
3828
+ "aborted",
3829
+ "query_timeout",
3830
+ "store_busy"
3831
+ ]);
3832
+ function transientRefusal(errors) {
3833
+ return (errors ?? []).some((e) => {
3834
+ const code = e?.code;
3835
+ return typeof code === "string" && TRANSIENT.has(code);
3836
+ });
3837
+ }
3838
+ /**
3524
3839
  * The Identity canonicalised, less `expiresAt`: a custom row policy may key on
3525
3840
  * any claim (a tenant, say), so no other subset is safe to share a cached pack
3526
3841
  * 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-KUFgRX_n.js";
1
+ import { n as bootstrap, t as NlBootstrapConfigSchema } from "./bootstrap-D1u015pv.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-KUFgRX_n.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-D1u015pv.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, runAs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AMtB,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;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;IAC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IACxB,sEAAsE;IACtE,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC;IACtB,yDAAyD;IACzD,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAqHD,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,aAAa,EACnB,GAAG,EAAE,YAAY,GAChB,WAAW,CA4bb;AAytBD,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.6",
3
+ "version": "1.0.0-beta.8",
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.6",
41
- "@mnmal-ai/substrate-config": "1.0.0-beta.6",
40
+ "@mnmal-ai/substrate": "1.0.0-beta.8",
41
+ "@mnmal-ai/substrate-config": "1.0.0-beta.8",
42
42
  "@types/node": "^26.6.4",
43
43
  "postgres": "4.1.0",
44
44
  "tsdown": "^0.23.0",