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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { METADATA_AUTHOR_FIELDS, METADATA_FILTER_FIELDS, ROW_POLICY_BLOCKS_WALK, WALKS_NEED_PARTITIONED, WALKS_UNSUPPORTED_STORE, defineBootstrap, error400, isImpossibleIsoTimestamp, isIsoTimestamp, jsonResponse, parseJsonBody, trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
1
+ import { METADATA_AUTHOR_FIELDS, METADATA_FILTER_FIELDS, ROW_POLICY_BLOCKS_WALK, WALKS_NEED_PARTITIONED, WALKS_UNSUPPORTED_STORE, defineBootstrap, error400, isImpossibleIsoTimestamp, isIsoTimestamp, jsonResponse, parseJsonBody, seesNamespace, trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
2
2
  import { z } from "zod";
3
3
  import { createHash } from "node:crypto";
4
4
  import { FRAMES_JSON_MIME, encodeStreamFrame, framesEncodingFromAccept } from "@mnmal-ai/substrate/pack";
@@ -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
+ }
337
370
  /**
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.
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
+ }
398
+ /**
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,16 @@ 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
+ end: aggregate.group.end ?? tokens.length
1709
+ } : null),
1551
1710
  aggregate,
1552
1711
  allProjects,
1553
1712
  historyWord,
@@ -1583,7 +1742,8 @@ function parseQuestion(question, pack, ctx) {
1583
1742
  residual: only.residual,
1584
1743
  reason: `dropped: ${only.dropped.map((d) => `"${d.span}" (${d.reason})`).join("; ")}`
1585
1744
  };
1586
- 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 {
1587
1747
  status: "partial",
1588
1748
  candidates,
1589
1749
  residual: only.residual,
@@ -1666,6 +1826,12 @@ function assemble(type, a) {
1666
1826
  reason: `${a.count ? "counting" : "aggregating"} over the latest N rows is not supported`,
1667
1827
  kind: "filter"
1668
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
+ }] : [],
1669
1835
  ...a.count && a.aggregate !== null ? [{
1670
1836
  span: a.aggregate.span,
1671
1837
  reason: "an aggregate does not apply to a count",
@@ -1742,7 +1908,14 @@ function assemble(type, a) {
1742
1908
  if (a.author !== null) where.push({ createdById: { startsWith: a.author } });
1743
1909
  const orderExclude = a.fieldOrder?.phrase?.entry.exclude;
1744
1910
  if (sortBy !== null && sortBy.hop === void 0 && orderExclude !== void 0) where.push({ NOT: orderExclude });
1745
- 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;
1746
1919
  if (agg !== null) {
1747
1920
  dropped.push(...agg.dropped);
1748
1921
  ev.push(...agg.evidence);
@@ -1881,11 +2054,23 @@ function assemble(type, a) {
1881
2054
  delete params.select;
1882
2055
  delete params.orderBy;
1883
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
+ }
1884
2068
  if (agg?.fn !== void 0 && agg.field !== void 0) {
1885
2069
  params.aggregate = { value: { [agg.fn]: agg.field } };
1886
2070
  if (agg.dateGroup !== void 0) params.groupBy = { bucket: { dateTrunc: [{ lit: agg.dateGroup.by }, agg.dateGroup.field] } };
1887
2071
  }
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";
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";
1889
2074
  return {
1890
2075
  type,
1891
2076
  frame: { [`${pack.namespace}/${type}`]: {
@@ -1897,18 +2082,30 @@ function assemble(type, a) {
1897
2082
  residual: contentWords(tokens),
1898
2083
  plan,
1899
2084
  dropped,
1900
- ...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: {
1901
2089
  fn: agg.fn,
1902
2090
  field: agg.field,
1903
2091
  ...agg.group !== void 0 ? { group: agg.group } : {}
1904
2092
  } } : {},
1905
- strict: a.count || aggClaim !== null || order !== null || sortBy !== null || a.ids.length === 1 || a.composed?.strict === true
2093
+ strict
1906
2094
  };
1907
2095
  }
1908
2096
  /** A field named by words on one type: one of its field phrases, else its name or an alias. */
1909
2097
  function fieldByWords(words, fields, rulings) {
1910
2098
  return Object.entries(fields).find(([, f]) => f.phrases.includes(words))?.[0] ?? (words.includes(" ") ? null : resolveField(words, fields, rulings));
1911
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
+ }
1912
2109
  /**
1913
2110
  * The field named at `i`: a field phrase claim, else the longest run of up to
1914
2111
  * three free words naming a field on some type, else (unless `numeric`) one
@@ -1925,10 +2122,7 @@ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1925
2122
  const slice = tokens.slice(i, i + n);
1926
2123
  if (slice.length < n || slice.some((t) => t.used)) continue;
1927
2124
  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 {
2125
+ if (namesField(w, Object.values(pack.types), rulings, numeric)) return {
1932
2126
  words: w,
1933
2127
  span: w,
1934
2128
  end: i + n - 1
@@ -1941,6 +2135,17 @@ function fieldAt(tokens, walkClaims, pack, rulings, i, numeric) {
1941
2135
  end: i
1942
2136
  } : null;
1943
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
+ }
1944
2149
  /** Marks tokens `from`..`f.end` used; a field phrase named here is not walked to. */
1945
2150
  function takeField(tokens, walkClaims, from, f) {
1946
2151
  for (let k = from; k <= f.end; k++) tokens[k].used = true;
@@ -2104,20 +2309,129 @@ const DIRECTION_WORDS = {
2104
2309
  };
2105
2310
  /** A field grouping runs one frame per value: more than this is dropped. */
2106
2311
  const MAX_GROUPS = 20;
2107
- const BUCKET_WORDS = /* @__PURE__ */ new Set([
2312
+ const TIME_UNITS = [
2108
2313
  "hour",
2109
2314
  "day",
2110
2315
  "week",
2111
2316
  "month",
2112
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 `word` asks for an aggregate or names a grouping unit ("average", "daily"). */
2330
+ function shapesAnswer(word) {
2331
+ return own(AGGREGATE_WORDS, word) !== void 0 || own(UNIT_ADJECTIVES, word) !== void 0;
2332
+ }
2333
+ /** Whether the token just before or after token `k` is an aggregate word, claimed or not. */
2334
+ function besideAggregate(tokens, k) {
2335
+ return [k - 1, k + 1].some((j) => own(AGGREGATE_WORDS, tokens[j]?.text ?? "") !== void 0);
2336
+ }
2337
+ /** The asked types and the types their crossRefs reach; every type when none is asked. */
2338
+ function askedTypes(pack, asked) {
2339
+ const seeds = asked.flatMap((t) => own(pack.types, t) ?? []);
2340
+ if (seeds.length === 0) return Object.values(pack.types);
2341
+ const reached = seeds.flatMap((t) => Object.values(t.fields).flatMap((f) => f.target?.namespace === pack.namespace ? own(pack.types, f.target.type) ?? [] : []));
2342
+ return [.../* @__PURE__ */ new Set([...seeds, ...reached])];
2343
+ }
2344
+ /**
2345
+ * The unit a free adjective at `k` names, unless it alone or with the next one or
2346
+ * two words, claimed or not, names a field of `names.types` ("annual fee", "annual total").
2347
+ */
2348
+ function adjectiveAt(tokens, k, names) {
2349
+ const t = tokens[k];
2350
+ const unit = t === void 0 || t.used ? void 0 : own(UNIT_ADJECTIVES, t.text);
2351
+ if (unit === void 0) return void 0;
2352
+ const words = tokens.slice(k, k + 3).map((x) => x.text);
2353
+ return [
2354
+ 1,
2355
+ 2,
2356
+ 3
2357
+ ].some((n) => namesField(words.slice(0, n).join(" "), names.types, names.rulings)) ? void 0 : unit;
2358
+ }
2359
+ /** Words that may follow a named date field without naming anything else ("by due date"). */
2360
+ const GENERIC_DATE_WORDS = /* @__PURE__ */ new Set([
2361
+ "date",
2362
+ "time",
2363
+ "day",
2364
+ "timestamp"
2113
2365
  ]);
2114
2366
  /**
2367
+ * Claims "by <date field>" right after a unit phrase ending at token `end` ("per month by due
2368
+ * date"): the longest run of up to three free words naming a date field, or a lone word that
2369
+ * starts exactly one date field's phrase ("due"), then one free generic date word the field's
2370
+ * own words do not hold ("due date" on `dueAt`). Anything else stays unread.
2371
+ */
2372
+ function claimDateField(tokens, end, fields, rulings) {
2373
+ const by = tokens[end + 1];
2374
+ if (by === void 0 || by.used || by.text !== "by") return null;
2375
+ const dates = Object.values(fields).filter((f) => f.valueType === "date");
2376
+ for (let n = 3; n >= 1; n--) {
2377
+ const slice = tokens.slice(end + 2, end + 2 + n);
2378
+ if (slice.length < n || slice.some((t) => t.used)) continue;
2379
+ const words = slice.map((t) => t.text).join(" ");
2380
+ const named = fieldByWords(words, fields, rulings);
2381
+ const starts = dates.filter((f) => f.phrases.some((p) => p.startsWith(`${words} `)));
2382
+ const name = named ?? (starts.length === 1 ? starts[0]?.name ?? null : null);
2383
+ const f = name === null ? void 0 : fields[name];
2384
+ if (name === null || f?.valueType !== "date") continue;
2385
+ const taken = [by, ...slice];
2386
+ const next = tokens[end + 2 + n];
2387
+ if (next !== void 0 && !next.used && GENERIC_DATE_WORDS.has(next.text) && !f.phrases.some((p) => p.split(" ").includes(next.text))) taken.push(next);
2388
+ for (const t of taken) t.used = true;
2389
+ return {
2390
+ name,
2391
+ taken
2392
+ };
2393
+ }
2394
+ return null;
2395
+ }
2396
+ /**
2397
+ * Claims "by|per <unit>" from token `from` on, skipping used tokens and "<author verb> by";
2398
+ * with `adjectives`, a unit adjective too, whichever comes first. With `awayFromAggregate`,
2399
+ * an adjective next to an aggregate word is skipped: that word did not claim it as its unit.
2400
+ */
2401
+ function claimUnit(tokens, from, adjectives, awayFromAggregate = false) {
2402
+ for (let k = from; k < tokens.length; k++) {
2403
+ const by = tokens[k];
2404
+ const adjective = adjectives === void 0 || awayFromAggregate && besideAggregate(tokens, k) ? void 0 : adjectiveAt(tokens, k, adjectives);
2405
+ if (adjective !== void 0) {
2406
+ by.used = true;
2407
+ return {
2408
+ span: by.text,
2409
+ unit: adjective,
2410
+ end: k
2411
+ };
2412
+ }
2413
+ if (by.used || by.text !== "by" && by.text !== "per") continue;
2414
+ if (AUTHOR_VERBS.has(tokens[k - 1]?.text ?? "")) continue;
2415
+ const next = tokens[k + 1];
2416
+ const unit = next === void 0 || next.used ? void 0 : TIME_UNITS.find((u) => u === next.text);
2417
+ if (next === void 0 || unit === void 0) continue;
2418
+ by.used = next.used = true;
2419
+ return {
2420
+ span: `${by.text} ${next.text}`,
2421
+ unit,
2422
+ end: k + 1
2423
+ };
2424
+ }
2425
+ return null;
2426
+ }
2427
+ /**
2115
2428
  * Claims one aggregate. "highest|lowest <field>" is a value only when "of" or
2116
2429
  * "for" follows the field and a type is named after it, none before the
2117
2430
  * superlative ("the highest price of items"); otherwise it stays an ordering
2118
2431
  * ("items with the highest price", "… highest price for last week").
2119
2432
  */
2120
- function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2433
+ function claimAggregate(tokens, walkClaims, pack, names, mentions) {
2434
+ const { rulings } = names;
2121
2435
  const ofFollows = (end) => VALUE_OF.has(tokens[end + 1]?.text ?? "");
2122
2436
  const valueAt = (start, end) => ofFollows(end) && mentions.some((m) => m > end) && !mentions.some((m) => m < start);
2123
2437
  for (let i = 0; i < tokens.length; i++) {
@@ -2135,11 +2449,14 @@ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2135
2449
  end: pick.phrase.at[1]
2136
2450
  };
2137
2451
  } else {
2138
- let j = i + 1;
2452
+ let j = adjectiveAt(tokens, i + 1, names) === void 0 ? i + 1 : i + 2;
2139
2453
  while (!(tokens[j]?.used ?? true) && (tokens[j]?.text === "of" || tokens[j]?.text === "the")) j++;
2140
2454
  f = fieldAt(tokens, walkClaims, pack, rulings, j, false);
2141
2455
  if (f === null || VALUE_SUPERLATIVES.has(t.text) && !valueAt(i, f.end)) continue;
2456
+ if (onlyBoolean(f.words, pack, rulings)) continue;
2142
2457
  }
2458
+ const beside = [i + 1, i - 1].find((k) => adjectiveAt(tokens, k, names) !== void 0);
2459
+ const besideUnit = beside === void 0 ? null : claimUnit(tokens, beside, names);
2143
2460
  takeField(tokens, walkClaims, i, f);
2144
2461
  const claim = {
2145
2462
  span: tokens.slice(i, f.end + 1).map((x) => x.text).join(" "),
@@ -2147,19 +2464,20 @@ function claimAggregate(tokens, walkClaims, pack, rulings, mentions) {
2147
2464
  fn,
2148
2465
  field: fieldRef(f)
2149
2466
  };
2467
+ const prev = tokens[i - 1];
2468
+ if (prev !== void 0 && !prev.used && own(UNIT_ADJECTIVES, prev.text) !== void 0) {
2469
+ prev.used = true;
2470
+ claim.held = prev.text;
2471
+ }
2472
+ const byUnit = besideUnit ?? claimUnit(tokens, 0);
2473
+ if (byUnit !== null) {
2474
+ claim.group = byUnit;
2475
+ return claim;
2476
+ }
2150
2477
  for (let k = 0; k < tokens.length; k++) {
2151
2478
  const by = tokens[k];
2152
2479
  if (by.used || by.text !== "by" && by.text !== "per") continue;
2153
2480
  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
2481
  const g = fieldAt(tokens, walkClaims, pack, rulings, k + 1, false);
2164
2482
  if (g === null) continue;
2165
2483
  takeField(tokens, walkClaims, k, g);
@@ -2197,13 +2515,14 @@ function seedField(o, type, pack, rulings, doing) {
2197
2515
  };
2198
2516
  }
2199
2517
  /** An aggregate claim read on `type`: its function and field, or drops saying why not. */
2200
- function aggregateOn(c, type, pack, rulings) {
2518
+ function aggregateOn(c, type, pack, rulings, bucketField) {
2201
2519
  const r = seedField({
2202
2520
  span: c.span,
2203
2521
  ...c.field
2204
2522
  }, type, pack, rulings, "aggregating");
2205
2523
  const wants = c.fn === "min" || c.fn === "max" ? ["number", "date"] : ["number"];
2206
- 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`;
2524
+ const accepts = (vt) => isNumeric(vt) || wants.length > 1 && vt === "date";
2525
+ 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`;
2207
2526
  if (reason !== null || "reason" in r) return {
2208
2527
  dropped: [{
2209
2528
  span: c.span,
@@ -2235,8 +2554,7 @@ function aggregateOn(c, type, pack, rulings) {
2235
2554
  return out;
2236
2555
  };
2237
2556
  if (g.unit !== void 0) {
2238
- if (g.unit !== "day" && g.unit !== "hour") return drop("only day and hour groupings are supported");
2239
- const field = own(rulings.timeField, type) ?? "createdAt";
2557
+ const field = bucketField ?? own(rulings.timeField, type) ?? "createdAt";
2240
2558
  out.dateGroup = {
2241
2559
  field,
2242
2560
  by: g.unit
@@ -2275,7 +2593,7 @@ function orderField(o, type, pack, rulings) {
2275
2593
  if ("reason" in r) return r;
2276
2594
  const { name, f } = r;
2277
2595
  if (o.pick !== void 0) return { reason: pickReason(o.pick, `${type}.${name}`, type) };
2278
- 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` };
2596
+ 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` };
2279
2597
  return { field: name };
2280
2598
  }
2281
2599
  /** Why a pick word cannot order: it is not a direction, or there is one value per seed row. */
@@ -2324,12 +2642,12 @@ function hopOrder(o, seed, to, pack, rulings) {
2324
2642
  if (path.length > 1) return { reason: `ordering across ${path.length} hops is not supported; one hop only` };
2325
2643
  const f = own(pack.types, to.type)?.fields[to.field];
2326
2644
  const qualified = `${to.type}.${to.field}`;
2327
- 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` };
2645
+ 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` };
2328
2646
  const h = path[0];
2329
2647
  if (o.pick !== void 0 && (h.dir === "out" || o.pick.kind !== "latest")) return { reason: pickReason(o.pick, qualified, seed) };
2330
2648
  const cap = to.field.charAt(0).toUpperCase() + to.field.slice(1);
2331
- const exclude = o.phrase?.entry.exclude;
2332
- const where = exclude !== void 0 ? { where: { NOT: exclude } } : {};
2649
+ const excludes = [o.phrase?.entry.exclude, own(rulings.typeExcludes, to.type)].flatMap((x) => x === void 0 ? [] : [{ NOT: x }]);
2650
+ const where = excludes.length === 0 ? {} : { where: excludes.length === 1 ? excludes[0] : { AND: excludes } };
2333
2651
  if (h.dir === "out") return { hop: {
2334
2652
  name: `${to.type.charAt(0).toLowerCase()}${to.type.slice(1)}${cap}`,
2335
2653
  agg: {
@@ -2368,6 +2686,11 @@ function coerce(raw, f) {
2368
2686
  const n = Number(raw);
2369
2687
  return Number.isFinite(n) ? n : void 0;
2370
2688
  }
2689
+ if (isNumeric(f.valueType)) {
2690
+ if (!/^-?\d+$/.test(raw)) return void 0;
2691
+ const n = Number(raw);
2692
+ return Number.isSafeInteger(n) ? n : BigInt(raw).toString();
2693
+ }
2371
2694
  if (f.valueType === "boolean") return raw === "true" ? true : raw === "false" ? false : void 0;
2372
2695
  return raw;
2373
2696
  }
@@ -2397,18 +2720,36 @@ function creditFieldWords(tokens, field) {
2397
2720
  }
2398
2721
  return hit;
2399
2722
  }
2723
+ /** Unexplained words, and a lone unread number, which no reading may lose. */
2400
2724
  function contentWords(tokens) {
2401
2725
  const free = (t) => t !== void 0 && !t.used && !GLUE.has(t.text);
2402
2726
  const num = (t) => free(t) && /^\d+$/.test(t.text);
2727
+ const word = (t) => free(t) && !num(t);
2403
2728
  const out = [];
2404
2729
  tokens.forEach((t, i) => {
2405
- if (!free(t) || num(t)) return;
2730
+ if (!free(t)) return;
2731
+ if (num(t)) {
2732
+ if (!word(tokens[i - 1]) && !word(tokens[i + 1])) out.push(t.text);
2733
+ return;
2734
+ }
2406
2735
  const before = num(tokens[i - 1]) ? `${tokens[i - 1]?.text} ` : "";
2407
2736
  const after = num(tokens[i + 1]) && !(free(tokens[i + 2]) && !num(tokens[i + 2])) ? ` ${tokens[i + 1]?.text}` : "";
2408
2737
  out.push(`${before}${t.text}${after}`);
2409
2738
  });
2410
2739
  return out;
2411
2740
  }
2741
+ /**
2742
+ * A pack value of up to four words, as the value pass reads, that takes in token `k` and
2743
+ * whose other words are free or in `span`: "may", "june 2025", "may release".
2744
+ */
2745
+ function valueAround(tokens, k, span, pack) {
2746
+ for (let n = 4; n >= 1; n--) for (let i = Math.max(0, k - n + 1); i <= k && i + n <= tokens.length; i++) {
2747
+ const slice = tokens.slice(i, i + n);
2748
+ if (slice.some((t, j) => t.used && (i + j < span[0] || i + j > span[1]))) continue;
2749
+ const key = slice.map((t) => t.text).join(" ");
2750
+ if (own(pack.values, key) !== void 0) return key;
2751
+ }
2752
+ }
2412
2753
  /** Claims the longest n-grams (up to `max` words) for which `accept` returns true. */
2413
2754
  function claimNgrams(tokens, max, accept) {
2414
2755
  for (let n = max; n >= 1; n--) for (let i = 0; i + n <= tokens.length; i++) {
@@ -2628,6 +2969,28 @@ function withBinding(rulings, choice) {
2628
2969
  }
2629
2970
  };
2630
2971
  }
2972
+ /** Verbs that say only that something took place, so they choose no date field. */
2973
+ const OCCURRED = /* @__PURE__ */ new Set([
2974
+ "happen",
2975
+ "happened",
2976
+ "happening",
2977
+ "occurred"
2978
+ ]);
2979
+ /**
2980
+ * Why a leftover word of a picked reading cannot be noise, or null. An aggregate
2981
+ * or unit word asks for a different answer, a word of one of the type's fields
2982
+ * names a filter or a column, and a word right before the time expression says
2983
+ * which date the window is on ("due in 2026"), unless it is one of OCCURRED.
2984
+ */
2985
+ function notNoise(word, question, chosen, pack) {
2986
+ const parts = word.split(" ");
2987
+ if (parts.some(shapesAnswer)) return "asks for an aggregate or a grouping";
2988
+ const fields = Object.values(own(pack.types, chosen.type)?.fields ?? {});
2989
+ const fieldWords = new Set(fields.flatMap((f) => [...splitWords(f.name), ...f.phrases.flatMap((p) => p.split(" "))]));
2990
+ if (parts.some((w) => fieldWords.has(w))) return `names a ${chosen.type} field`;
2991
+ const q = question.toLowerCase();
2992
+ return !OCCURRED.has(word) && chosen.evidence.some((e) => e.role === "time" && q.includes(`${word} ${e.span.toLowerCase()}`)) ? "says which date is meant" : null;
2993
+ }
2631
2994
  /** Why a binding cannot be applied, or null when it grounds. */
2632
2995
  async function verifyBinding(choice, earlier, pack, opts) {
2633
2996
  const [type, field] = choice.field.split(".");
@@ -2697,8 +3060,23 @@ async function parseWithJudge(question, pack, ctx, judge, opts = {}) {
2697
3060
  trail
2698
3061
  };
2699
3062
  }
2700
- if (chosen.strict && chosen.residual.length > 0) {
2701
- const reason = `unexplained under a strict reading: ${chosen.residual.join(", ")}`;
3063
+ const digits = chosen.residual.filter((w) => /\d/.test(w));
3064
+ if (chosen.strict && chosen.residual.length > 0 || digits.length > 0) {
3065
+ const reason = chosen.strict ? `unexplained under a strict reading: ${chosen.residual.join(", ")}` : `a digit is never noise: ${digits.join(", ")}`;
3066
+ return {
3067
+ status: "escalated",
3068
+ result: {
3069
+ status: "partial",
3070
+ candidates: [chosen],
3071
+ residual: chosen.residual,
3072
+ reason
3073
+ },
3074
+ trail
3075
+ };
3076
+ }
3077
+ const meant = chosen.residual.map((w) => [w, notNoise(w, question, chosen, pack)]).filter(([, why]) => why !== null);
3078
+ if (meant.length > 0) {
3079
+ const reason = `not noise: ${meant.map(([w, why]) => `"${w}" ${why}`).join("; ")}`;
2702
3080
  return {
2703
3081
  status: "escalated",
2704
3082
  result: {
@@ -2839,7 +3217,7 @@ function mergePlan(parsed, engine) {
2839
3217
  }
2840
3218
  async function rows(c, source, question, http, deps, handoff, leftovers = []) {
2841
3219
  const dropped = [...c.dropped, ...leftovers];
2842
- if (c.strict && dropped.some((d) => d.kind === "filter")) return {
3220
+ if ((c.strict || source === "handoff") && dropped.some((d) => d.kind === "filter")) return {
2843
3221
  kind: "unknown",
2844
3222
  question,
2845
3223
  dropped,
@@ -2876,6 +3254,14 @@ async function rows(c, source, question, http, deps, handoff, leftovers = []) {
2876
3254
  plan: mergePlan(c.plan, env._diagnostics?.[key]?.plan)
2877
3255
  };
2878
3256
  }
3257
+ /** Characters of the engine's canonical instant that name a group of each unit. */
3258
+ const LABEL_LENGTH = {
3259
+ hour: 13,
3260
+ day: 10,
3261
+ week: 10,
3262
+ month: 7,
3263
+ year: 4
3264
+ };
2879
3265
  /**
2880
3266
  * An aggregate answer: the engine's one frame, or, grouped by a field the
2881
3267
  * engine cannot group, one frame per value of it.
@@ -2914,8 +3300,9 @@ async function aggregate(c, frame, key, source, http, deps, dropped, handoff) {
2914
3300
  }
2915
3301
  const trunc = params.groupBy?.bucket?.dateTrunc;
2916
3302
  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;
3303
+ const short = (k) => typeof k === "string" && trunc !== void 0 ? k.slice(0, LABEL_LENGTH[trunc[0].lit]) : k;
2918
3304
  const rows = data?.groups;
3305
+ const wire = (v) => typeof v === "bigint" ? v.toString() : v;
2919
3306
  const result = rows === void 0 ? void 0 : {
2920
3307
  fn,
2921
3308
  field,
@@ -2923,9 +3310,9 @@ async function aggregate(c, frame, key, source, http, deps, dropped, handoff) {
2923
3310
  by,
2924
3311
  groups: rows.filter((g) => trunc === void 0 || g.bucket !== null).map((g) => ({
2925
3312
  key: short(g.bucket ?? g.key),
2926
- value: g.value
3313
+ value: wire(g.value)
2927
3314
  }))
2928
- } : { value: rows[0]?.value ?? null },
3315
+ } : { value: wire(rows[0]?.value ?? null) },
2929
3316
  ...data?.truncated === true ? { truncated: true } : {}
2930
3317
  };
2931
3318
  return {
@@ -2969,6 +3356,15 @@ async function countRest(frame, key, seen, first, http, deps) {
2969
3356
  }
2970
3357
  return count;
2971
3358
  }
3359
+ /** The row fields `ask` returns per recall hit: enough to name and pick a row. */
3360
+ const HIT_ROW = {
3361
+ shortId: true,
3362
+ name: true,
3363
+ title: true,
3364
+ topic: true,
3365
+ synopsis: true,
3366
+ description: true
3367
+ };
2972
3368
  async function recall(query, ns, type, http, deps) {
2973
3369
  const frame = { "recall/Hit": {
2974
3370
  params: {
@@ -2982,7 +3378,7 @@ async function recall(query, ns, type, http, deps) {
2982
3378
  namespace: true,
2983
3379
  type: true,
2984
3380
  score: true,
2985
- row: true
3381
+ row: HIT_ROW
2986
3382
  }
2987
3383
  } };
2988
3384
  const env = await deps.engine.query(frame, http);
@@ -3250,22 +3646,25 @@ function buildNamespacePack(input) {
3250
3646
  const def = declared[name];
3251
3647
  const field = packField(name, def, operators);
3252
3648
  fields[name] = field;
3649
+ const observed = profile?.types[typeName]?.[name];
3650
+ const counted = (value) => observed?.counts === void 0 ? {} : { count: own(observed.counts, value) ?? 0 };
3253
3651
  for (const value of field.enum ?? []) refs.push({
3254
3652
  type: typeName,
3255
3653
  field: name,
3256
- value
3654
+ value,
3655
+ ...counted(value)
3257
3656
  });
3258
3657
  for (const alias of Object.keys(field.aliases ?? {})) refs.push({
3259
3658
  type: typeName,
3260
3659
  field: name,
3261
3660
  value: alias
3262
3661
  });
3263
- const observed = profile?.types[typeName]?.[name];
3264
3662
  if (observed !== void 0 && field.indexed && isStringy(def) && !observed.truncated && observed.values.length <= maxDistinct && areLabels(observed.values)) {
3265
3663
  for (const value of observed.values) refs.push({
3266
3664
  type: typeName,
3267
3665
  field: name,
3268
- value
3666
+ value,
3667
+ ...counted(value)
3269
3668
  });
3270
3669
  field.distinct = observed.values.length;
3271
3670
  }
@@ -3376,7 +3775,8 @@ function sortKeys(obj) {
3376
3775
  /**
3377
3776
  * Distinct values of every indexed string field (and indexed list-of-string
3378
3777
  * field) in the namespace, reading up to `maxRows` rows per type. A field that
3379
- * passes `maxDistinct` is marked truncated and stops growing.
3778
+ * passes `maxDistinct` is marked truncated and stops growing. A field carries
3779
+ * per-value row counts only when every row of its type was read.
3380
3780
  */
3381
3781
  async function profileNamespace(input) {
3382
3782
  const maxDistinct = input.maxDistinct ?? 1e3;
@@ -3386,7 +3786,7 @@ async function profileNamespace(input) {
3386
3786
  const declared = input.schema.types[typeName]?.fields ?? {};
3387
3787
  const fields = Object.keys(declared).filter((f) => profiled(declared[f]));
3388
3788
  if (fields.length === 0) continue;
3389
- const seen = new Map(fields.map((f) => [f, /* @__PURE__ */ new Set()]));
3789
+ const seen = new Map(fields.map((f) => [f, /* @__PURE__ */ new Map()]));
3390
3790
  const truncated = /* @__PURE__ */ new Set();
3391
3791
  let cursor;
3392
3792
  let rowsRead = 0;
@@ -3396,11 +3796,11 @@ async function profileNamespace(input) {
3396
3796
  for (const row of page.rows) for (const f of fields) {
3397
3797
  if (truncated.has(f)) continue;
3398
3798
  const raw = row[f];
3399
- const values = Array.isArray(raw) ? raw : [raw];
3799
+ const values = Array.isArray(raw) ? new Set(raw) : [raw];
3400
3800
  const set = seen.get(f);
3401
3801
  for (const v of values) {
3402
3802
  if (typeof v !== "string" || v.length === 0) continue;
3403
- set.add(v);
3803
+ set.set(v, (set.get(v) ?? 0) + 1);
3404
3804
  if (set.size > maxDistinct) {
3405
3805
  truncated.add(f);
3406
3806
  break;
@@ -3411,12 +3811,14 @@ async function profileNamespace(input) {
3411
3811
  } while (cursor !== void 0 && truncated.size < fields.length && rowsRead < maxRows);
3412
3812
  const out = {};
3413
3813
  for (const f of [...fields].sort()) {
3414
- const values = [...seen.get(f)].sort();
3814
+ const counted = seen.get(f);
3815
+ const values = [...counted.keys()].sort();
3415
3816
  const isTruncated = truncated.has(f);
3416
3817
  if (values.length === 0 && !isTruncated) continue;
3417
3818
  out[f] = {
3418
3819
  values: isTruncated ? values.slice(0, maxDistinct) : values,
3419
- truncated: isTruncated
3820
+ truncated: isTruncated,
3821
+ ...cursor === void 0 && !isTruncated ? { counts: Object.fromEntries(counted) } : {}
3420
3822
  };
3421
3823
  }
3422
3824
  types[typeName] = out;
@@ -3446,7 +3848,7 @@ var PackService = class {
3446
3848
  }
3447
3849
  async get(ns, req) {
3448
3850
  const schemas = this.#opts.engine.federatedSchema();
3449
- const schema = Object.hasOwn(schemas, ns) ? schemas[ns] : void 0;
3851
+ const schema = Object.hasOwn(schemas, ns) && seesNamespace(req.identity, ns) ? schemas[ns] : void 0;
3450
3852
  if (schema === void 0) return void 0;
3451
3853
  const now = (this.#opts.now ?? Date.now)();
3452
3854
  const ttl = this.#opts.ttlMs ?? 3e5;
@@ -3492,7 +3894,9 @@ var PackService = class {
3492
3894
  params: cursor !== void 0 ? { cursor } : {},
3493
3895
  fields: Object.fromEntries(fields.map((f) => [f, true]))
3494
3896
  } }, req);
3897
+ if (req.signal?.aborted === true) throw new Error(`pack build for '${ns}' was cancelled`);
3495
3898
  const rows = env.data?.[frameKey];
3899
+ if (rows === void 0 && transientRefusal(env.errors)) throw new Error(`pack build: reading ${frameKey} failed: ${JSON.stringify(env.errors ?? [])}`);
3496
3900
  const page = env._pagination?.[frameKey];
3497
3901
  return {
3498
3902
  rows: Array.isArray(rows) ? rows : [],
@@ -3521,13 +3925,28 @@ var PackService = class {
3521
3925
  }
3522
3926
  };
3523
3927
  /**
3928
+ * Refusals that may not recur on the next build. Any other refusal (a policy
3929
+ * denial, a type that only streams) is lasting, and leaves the type's values out.
3930
+ */
3931
+ const TRANSIENT = /* @__PURE__ */ new Set([
3932
+ "aborted",
3933
+ "query_timeout",
3934
+ "store_busy"
3935
+ ]);
3936
+ function transientRefusal(errors) {
3937
+ return (errors ?? []).some((e) => {
3938
+ const code = e?.code;
3939
+ return typeof code === "string" && TRANSIENT.has(code);
3940
+ });
3941
+ }
3942
+ /**
3524
3943
  * The Identity canonicalised, less `expiresAt`: a custom row policy may key on
3525
3944
  * any claim (a tenant, say), so no other subset is safe to share a cached pack
3526
3945
  * across, while a token's expiry changes with every refresh.
3527
3946
  */
3528
3947
  function principalKey(req) {
3529
3948
  const id = req.identity;
3530
- if (id === void 0) return "\0anon";
3949
+ if (id === void 0 || id === null) return "\0anon";
3531
3950
  const { expiresAt: _expiresAt, ...stable } = id;
3532
3951
  return JSON.stringify(canonical(stable));
3533
3952
  }
@@ -3713,7 +4132,8 @@ function createNlPlugin(cfg) {
3713
4132
  path: "nl",
3714
4133
  method: "POST",
3715
4134
  handler: askHandler(deps),
3716
- capability: "read"
4135
+ capability: "read",
4136
+ maxInFlightPerCaller: cfg.inFlightPerCaller ?? 4
3717
4137
  }, {
3718
4138
  path: "nl/pack/:ns",
3719
4139
  method: "GET",
@@ -3733,6 +4153,7 @@ function createNlPlugin(cfg) {
3733
4153
  * every escalation is an honest hand-off.
3734
4154
  * - `rulings` optional; per-namespace override merged over declared rulings.
3735
4155
  * - `packTtlMs` how long a served pack is reused. Default 300000.
4156
+ * - `inFlightPerCaller` asks one caller may have running at once. Default 4.
3736
4157
  * Host-supplied (`hostDeps.nlEngine`): schema, operators and query access.
3737
4158
  */
3738
4159
  const JudgeSchema = z.object({
@@ -3743,13 +4164,15 @@ const JudgeSchema = z.object({
3743
4164
  const NlBootstrapConfigSchema = z.object({
3744
4165
  judge: JudgeSchema.optional(),
3745
4166
  rulings: z.record(z.string(), NamespaceRulingsSchema).optional(),
3746
- packTtlMs: z.number().int().positive().default(3e5)
4167
+ packTtlMs: z.number().int().positive().default(3e5),
4168
+ inFlightPerCaller: z.number().int().positive().default(4)
3747
4169
  }).strict();
3748
4170
  const bootstrap = defineBootstrap.kernel({
3749
4171
  schema: NlBootstrapConfigSchema,
3750
4172
  build: (config, deps) => createNlPlugin({
3751
4173
  engine: deps.nlEngine,
3752
4174
  packTtlMs: config.packTtlMs,
4175
+ inFlightPerCaller: config.inFlightPerCaller,
3753
4176
  ...config.judge !== void 0 ? {
3754
4177
  judge: new OllamaJudge(config.judge),
3755
4178
  judgeTimeoutMs: config.judge.timeoutMs