@graview/tools 0.1.18 → 0.1.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.
Files changed (63) hide show
  1. package/README.md +47 -0
  2. package/dist/agent/tools.d.ts +37 -0
  3. package/dist/agent/tools.d.ts.map +1 -1
  4. package/dist/agent/tools.js +87 -15
  5. package/dist/agent/tools.js.map +1 -1
  6. package/dist/ai.d.ts +64 -0
  7. package/dist/ai.d.ts.map +1 -0
  8. package/dist/ai.js +11 -0
  9. package/dist/ai.js.map +1 -0
  10. package/dist/capital.d.ts +3 -0
  11. package/dist/capital.d.ts.map +1 -0
  12. package/dist/capital.js +3 -0
  13. package/dist/capital.js.map +1 -0
  14. package/dist/conversation.d.ts +36 -12
  15. package/dist/conversation.d.ts.map +1 -1
  16. package/dist/conversation.js +95 -31
  17. package/dist/conversation.js.map +1 -1
  18. package/dist/dev-ai.d.ts +27 -0
  19. package/dist/dev-ai.d.ts.map +1 -0
  20. package/dist/dev-ai.js +48 -0
  21. package/dist/dev-ai.js.map +1 -0
  22. package/dist/draft.d.ts +194 -0
  23. package/dist/draft.d.ts.map +1 -0
  24. package/dist/draft.js +1083 -0
  25. package/dist/draft.js.map +1 -0
  26. package/dist/frame.d.ts +6 -6
  27. package/dist/frame.d.ts.map +1 -1
  28. package/dist/frame.js +5 -5
  29. package/dist/frame.js.map +1 -1
  30. package/dist/go.d.ts +177 -0
  31. package/dist/go.d.ts.map +1 -0
  32. package/dist/go.js +839 -0
  33. package/dist/go.js.map +1 -0
  34. package/dist/index.d.ts +7 -3
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +4 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/intelligence.d.ts.map +1 -1
  39. package/dist/intelligence.js +2 -2
  40. package/dist/intelligence.js.map +1 -1
  41. package/dist/keep.d.ts +45 -0
  42. package/dist/keep.d.ts.map +1 -0
  43. package/dist/keep.js +86 -0
  44. package/dist/keep.js.map +1 -0
  45. package/dist/local.d.ts +50 -42
  46. package/dist/local.d.ts.map +1 -1
  47. package/dist/local.js +104 -146
  48. package/dist/local.js.map +1 -1
  49. package/dist/providers/schema.d.ts.map +1 -1
  50. package/dist/providers/schema.js +7 -7
  51. package/dist/providers/schema.js.map +1 -1
  52. package/dist/providers/structure.d.ts.map +1 -1
  53. package/dist/providers/structure.js +2 -2
  54. package/dist/providers/structure.js.map +1 -1
  55. package/dist/suggest.d.ts +102 -0
  56. package/dist/suggest.d.ts.map +1 -0
  57. package/dist/suggest.js +234 -0
  58. package/dist/suggest.js.map +1 -0
  59. package/package.json +19 -3
  60. package/dist/rungs.d.ts +0 -73
  61. package/dist/rungs.d.ts.map +0 -1
  62. package/dist/rungs.js +0 -60
  63. package/dist/rungs.js.map +0 -1
package/dist/go.js ADDED
@@ -0,0 +1,839 @@
1
+ import { brokenWords, edgeWords, kindPath, labelOf, nounOf, placesFrom, pluralOf as pluralOfKind, recordPath, readableFields, search, squeeze, violationsTouching, withArticle, } from "@graview/core";
2
+ import { arrangeable, conditionHolds } from "@graview/core/arrange";
3
+ import { readyRepairsOf } from "./conversation.js";
4
+ import { validateProposals } from "./intelligence.js";
5
+ import { capitalize } from "./capital.js";
6
+ export const NOTHING_BY_THAT_NAME = "Nothing by that name here.";
7
+ /* ------------------------------------------------------------------ words */
8
+ const fold = (text) => text
9
+ .normalize("NFD")
10
+ .replace(/\p{M}+/gu, "")
11
+ .toLowerCase()
12
+ .replace(/[’']/g, "'")
13
+ .replace(/[^\p{L}\p{N}' ]+/gu, " ")
14
+ .replace(/\s+/g, " ")
15
+ .trim();
16
+ /** The words that ask to be taken somewhere. */
17
+ const GO = /^(?:(?:can you |could you |please )?(?:go|take me|bring me|head|jump|navigate|switch|get me)(?: back)? to|(?:please )?(?:open|show(?: me)?|bring up|let me see|view)) (.+)$/;
18
+ /** The words that ask to be told about something. */
19
+ const TELL = /^(?:(?:can you |could you |please )?tell me (?:about|of)|what(?: is|'s| are) (?:in |on )?|describe|explain|who(?: is|'s)) (.+)$/;
20
+ /** "What is here", in the ways it is asked. */
21
+ const HERE = /^(?:what(?: is|'s| am i looking at| do i see)(?: (?:here|this|on (?:this|the) (?:page|screen)|in view|this place|this page))?|where am i|describe (?:this|here|this place|this page)|tell me about (?:this|here|this place|this page))$/;
22
+ const HERE_WORDS = new Set(["here", "this", "this place", "this page", "on this page", "on the page", "on this screen", "in view"]);
23
+ /** A date field whose name only means "when": said as the date words alone. */
24
+ const JUST_WHEN = /^(?:date|day|when|on|at|the date|the day)$/;
25
+ /** "What's wrong", and the record it may be about. */
26
+ const WRONG = /^(?:what(?: is|'s) (?:wrong|broken|the (?:problem|matter|trouble))|what needs (?:fixing|attention|doing)|any (?:problems|issues|trouble)|(?:show(?: me)? |go to |open )?(?:the )?(?:problems|issues|trouble|standing|what's wrong)|is (?:anything|something) (?:wrong|broken)|are there (?:any )?(?:problems|issues))(?: (?:with|about|on|in) (.+))?$/;
27
+ const stripThe = (text) => text.replace(/^(?:the|a|an|my|our) /, "");
28
+ /** Words that can sit around a kind and its filter without changing what is asked. */
29
+ const FILLER = new Set([
30
+ "the", "a", "an", "my", "our", "all", "any", "of", "that", "which", "who", "are", "is", "be", "what", "whats", "what's", "with",
31
+ "me", "show", "list", "every", "there", "do", "i", "have", "we", "due", "for", "please", "were", "was", "by", "from", "in", "on",
32
+ ]);
33
+ /* ------------------------------------------------------------------- days */
34
+ const DAY_MS = 86_400_000;
35
+ const parseDay = (day) => Date.UTC(Number(day.slice(0, 4)), Number(day.slice(5, 7)) - 1, Number(day.slice(8, 10)));
36
+ const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
37
+ const addDays = (day, days) => dayOf(parseDay(day) + days * DAY_MS);
38
+ const WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
39
+ const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
40
+ const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
41
+ /** A weekday as it is said, with the two shortenings nobody confuses with another word. */
42
+ const WEEKDAY = "(monday|tuesday|tues|wednesday|thursday|thurs|friday|saturday|sunday)";
43
+ /** A month as it is said: whole, or its first three letters ("sept" too). */
44
+ const MONTH = "(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sept|sep|oct|nov|dec)";
45
+ const ORDINAL = "(\\d{1,2})(?:st|nd|rd|th)?";
46
+ const weekdayOf = (word) => WEEKDAYS.findIndex((name) => name.startsWith(word.slice(0, 3)));
47
+ const monthOf = (word) => MONTH_NAMES.findIndex((name) => word.startsWith(name.toLowerCase()));
48
+ /** "Thursday 17 Sep", and the year when it is not this one. */
49
+ function dayWords(day, today) {
50
+ const at = new Date(parseDay(day));
51
+ const year = day.slice(0, 4) === today.slice(0, 4) ? "" : ` ${day.slice(0, 4)}`;
52
+ return `${WEEKDAY_NAMES[at.getUTCDay()]} ${at.getUTCDate()} ${MONTH_NAMES[at.getUTCMonth()]}${year}`;
53
+ }
54
+ /** A day of a month with no year: this year's, unless that was half a year ago — then next year's. */
55
+ function nearestDate(month, date, today) {
56
+ if (month < 0 || date < 1 || date > 31)
57
+ return undefined;
58
+ const year = Number(today.slice(0, 4));
59
+ const on = (y) => {
60
+ const ms = Date.UTC(y, month, date);
61
+ return new Date(ms).getUTCMonth() === month ? dayOf(ms) : undefined;
62
+ };
63
+ const here = on(year);
64
+ if (!here)
65
+ return undefined;
66
+ return parseDay(here) < parseDay(today) - 183 * DAY_MS ? on(year + 1) : here;
67
+ }
68
+ /**
69
+ * The date words in an ask, against today: today, tomorrow, yesterday, a
70
+ * weekday ("thursday", "on friday", "next tuesday", "last monday"), this or
71
+ * next week or weekend, this month, overdue, and a date ("12 Oct", "Oct
72
+ * 12th", "2026-10-12"). Only shapes a person says; nothing is guessed.
73
+ */
74
+ function readDate(asked, today, weekStartsOn) {
75
+ const weekday = new Date(parseDay(today)).getUTCDay();
76
+ const week = (offset) => {
77
+ const back = (weekday - weekStartsOn + 7) % 7;
78
+ const first = addDays(today, -back + offset * 7);
79
+ return { from: first, to: addDays(first, 6) };
80
+ };
81
+ const month = () => {
82
+ const first = `${today.slice(0, 8)}01`;
83
+ const next = new Date(Date.UTC(Number(today.slice(0, 4)), Number(today.slice(5, 7)), 1));
84
+ return { from: first, to: addDays(dayOf(next.getTime()), -1) };
85
+ };
86
+ const one = (day) => (day ? { from: day, to: day, day: dayWords(day, today) } : undefined);
87
+ /** A weekday: in this week or the next one when said so, else the next such day from today (today included), or the last one before it. */
88
+ const named = (which, name) => {
89
+ const wanted = weekdayOf(name);
90
+ if (which === "this" || which === "next")
91
+ return one(addDays(week(which === "next" ? 1 : 0).from, (wanted - weekStartsOn + 7) % 7));
92
+ if (which === "last")
93
+ return one(addDays(today, -(((weekday - wanted + 6) % 7) + 1)));
94
+ return one(addDays(today, (wanted - weekday + 7) % 7));
95
+ };
96
+ /** Saturday and Sunday: the coming ones, or the ones we are in. */
97
+ const weekend = (offset) => {
98
+ const saturday = addDays(today, weekday === 0 ? -1 : 6 - weekday);
99
+ return { from: addDays(saturday, offset * 7), to: addDays(saturday, offset * 7 + 1) };
100
+ };
101
+ const lead = "\\b(?:(?:due |for |on |by )(?:the )?)?";
102
+ const shapes = [
103
+ [/\b(?:overdue|past due|late)\b/, () => ({ overdue: true, to: addDays(today, -1) })],
104
+ [/\b(?:due |for |on )?today\b/, () => ({ from: today, to: today })],
105
+ [/\b(?:due |for |on )?tomorrow\b/, () => one(addDays(today, 1))],
106
+ [/\b(?:due |for |on )?yesterday\b/, () => one(addDays(today, -1))],
107
+ [/\b(?:due |for |on )?this week\b/, () => week(0)],
108
+ [/\b(?:due |for |on )?next week\b/, () => week(1)],
109
+ [/\b(?:due |for |on )?(?:last|previous) week\b/, () => week(-1)],
110
+ [/\b(?:due |for |on )?next weekend\b/, () => weekend(1)],
111
+ [/\b(?:due |for |on )?(?:this |the )?weekend\b/, () => weekend(0)],
112
+ [/\b(?:due |for |on )?this month\b/, () => month()],
113
+ [new RegExp(`${lead}(\\d{4}) (\\d{2}) (\\d{2})\\b`), (found) => one(nearestDate(Number(found[2]) - 1, Number(found[3]), `${found[1]}-01-01`))],
114
+ [new RegExp(`${lead}${ORDINAL} (?:of )?${MONTH}\\b`), (found) => one(nearestDate(monthOf(found[2]), Number(found[1]), today))],
115
+ [new RegExp(`${lead}${MONTH} (?:the )?${ORDINAL}\\b`), (found) => one(nearestDate(monthOf(found[1]), Number(found[2]), today))],
116
+ [new RegExp(`${lead}(?:(this|next|last|coming) )?${WEEKDAY}\\b`), (found) => named(found[1], found[2])],
117
+ ];
118
+ for (const [shape, range] of shapes) {
119
+ const found = asked.match(shape);
120
+ if (!found)
121
+ continue;
122
+ const read = range(found);
123
+ if (!read)
124
+ continue;
125
+ return { ask: { words: found[0], ...read }, rest: asked.replace(found[0], " ").replace(/\s+/g, " ").trim() };
126
+ }
127
+ return undefined;
128
+ }
129
+ /* --------------------------------------------------------------- the seat */
130
+ /**
131
+ * Reads an ask as one of the five, against one seat's sight.
132
+ *
133
+ * `store` may be the whole store or a seat's view of it; it is read through
134
+ * `context.principal` either way.
135
+ */
136
+ export function resolveAsk(store, text, context = {}) {
137
+ const principal = context.principal ?? { kind: "human" };
138
+ const seen = store.seenBy(principal);
139
+ const schema = seen.schema;
140
+ // The day asked about: the one handed in, else the day the store is judged on, else the real one.
141
+ const today = context.today ?? store.today?.() ?? new Date().toISOString().slice(0, 10);
142
+ const weekStartsOn = context.weekStartsOn ?? 1;
143
+ const kept = store.kindsKeptFrom(principal);
144
+ const off = store.modules.disabledKinds;
145
+ const visibleKinds = schema.kinds.filter((kind) => !kept.has(kind) && !off.has(kind));
146
+ const visible = new Set(visibleKinds);
147
+ const places = (context.places ?? []).filter((place) => place.kind === null || visible.has(place.kind));
148
+ const graph = seen.graph;
149
+ const asked = fold(text).replace(/[?.!]+$/, "").trim();
150
+ if (asked.length === 0)
151
+ return { unresolved: true };
152
+ const definitionOf = (kind) => schema.tryDefinition(kind);
153
+ const nameOf = (node) => labelOf(definitionOf(node.kind), node);
154
+ const pluralOf = (kind) => pluralOfKind(schema, kind);
155
+ const listAddress = (kind) => places.find((place) => place.kind === kind && place.address === kindPath(schema, kind))?.address ?? kindPath(schema, kind);
156
+ const recordAddress = (node) => recordPath(schema, node.kind, node.id);
157
+ const toRecord = (node) => ({
158
+ to: "record",
159
+ id: node.id,
160
+ kind: node.kind,
161
+ label: nameOf(node),
162
+ address: recordAddress(node),
163
+ said: `Went to ${nameOf(node)}.`,
164
+ });
165
+ const toPlace = (place) => {
166
+ const said = `Went to ${place.title}.`;
167
+ if (place.kind === null) {
168
+ return { to: "place", slug: place.slug, title: place.title, address: place.address, ...(place.slug === "overview" ? { face: "scene" } : {}), said };
169
+ }
170
+ if (place.lens || place.address.startsWith("/places/")) {
171
+ return { to: "picture", kind: place.kind, as: place.slug, title: place.title, address: place.address, said };
172
+ }
173
+ return { to: "kind", kind: place.kind, title: place.title, address: place.address, said };
174
+ };
175
+ const nothing = () => ({ unresolved: true, say: NOTHING_BY_THAT_NAME });
176
+ /** A short, true sentence about one record: what it is, three facts, and its trouble. */
177
+ const describeRecord = (node) => {
178
+ const definition = definitionOf(node.kind);
179
+ const facts = readableFields(node, definition, { limit: 3 })
180
+ .map((field) => (field.alone.startsWith(field.label) ? field.alone : `${field.label.toLowerCase()} ${field.alone}`))
181
+ .join(", ");
182
+ const trouble = seen.violations().filter((violation) => violation.nodeIds.includes(node.id));
183
+ return [
184
+ `${nameOf(node)} — ${withArticle(nounOf(definition, node.kind))}${facts ? ` (${facts})` : ""}.`,
185
+ trouble.length > 0 ? `Trouble: ${trouble.map((violation) => violation.message).join("; ")}.` : "",
186
+ ]
187
+ .filter(Boolean)
188
+ .join(" ");
189
+ };
190
+ /** A place by its title, its slug, or its title without "the". */
191
+ const placeNamed = (words) => {
192
+ const wanted = new Set([squeeze(words), squeeze(stripThe(words))]);
193
+ for (const suffix of [" page", " view", " lens", " place", " picture", " list"]) {
194
+ if (words.endsWith(suffix)) {
195
+ wanted.add(squeeze(words.slice(0, -suffix.length)));
196
+ wanted.add(squeeze(stripThe(words.slice(0, -suffix.length))));
197
+ }
198
+ }
199
+ wanted.delete("");
200
+ const named = (place) => wanted.has(squeeze(place.title)) || wanted.has(squeeze(stripThe(fold(place.title)))) || wanted.has(squeeze(place.slug));
201
+ // A lens place before a kind's list of the same name; the first of several kinds that share a picture.
202
+ return places.find((place) => place.kind !== null && place.address.startsWith("/places/") && named(place)) ?? places.find(named);
203
+ };
204
+ /** Records by name, under the seat's sight: the one meant, or the several the words find. */
205
+ const recordsNamed = (words) => {
206
+ const found = search(store, words, { principal, today, limit: 6, ...(context.selection ? { from: context.selection } : {}) });
207
+ const picks = found.hits.filter((hit) => hit.about === "node" && visible.has(hit.kind) && graph.getNode(hit.id) !== undefined);
208
+ const exact = picks.filter((hit) => hit.why.field === "label" && hit.why.strength === "exact");
209
+ if (exact.length === 1)
210
+ return { one: graph.getNode(exact[0].id), picks };
211
+ if (exact.length > 1)
212
+ return { picks: exact };
213
+ if (picks.length === 1 && found.total === 1)
214
+ return { one: graph.getNode(picks[0].id), picks };
215
+ return { picks };
216
+ };
217
+ const picksSaid = (picks) => {
218
+ const names = picks.map((hit) => `${hit.label} (${nounOf(definitionOf(hit.kind), hit.kind)})`);
219
+ return `${picks.length === 1 ? "One thing matches" : `${picks.length} things match`}: ${names.join("; ")}.`;
220
+ };
221
+ /** Go to a place or a record by name, or say nothing is called that. */
222
+ const goNamed = (words, describe) => {
223
+ if (HERE_WORDS.has(words))
224
+ return here();
225
+ /*
226
+ * TOLD ABOUT A THING, THE THING. A picture is often named after the
227
+ * record it draws ("Email to Todd" on Cloud's workshop): asked to be told
228
+ * about it, the seat went to the picture and counted its records — "2
229
+ * deliverables are here" — instead of saying what the email is.
230
+ */
231
+ const named = describe ? recordsNamed(stripThe(words) || words) : undefined;
232
+ const place = named?.one && fold(nameOf(named.one)) === fold(stripThe(words) || words) ? undefined : placeNamed(words);
233
+ if (place) {
234
+ const move = toPlace(place);
235
+ return { about: "place", say: describe ? `${move.said} ${describePlace(place)}` : move.said, moves: [move], subject: place.slug };
236
+ }
237
+ const records = recordsNamed(stripThe(words) || words);
238
+ if (records.one) {
239
+ const move = toRecord(records.one);
240
+ return { about: describe ? "describe" : "record", say: describe ? `${move.said} ${describeRecord(records.one)}` : move.said, moves: [move], subject: records.one.id };
241
+ }
242
+ if (records.picks.length > 0)
243
+ return { about: "picks", say: picksSaid(records.picks), moves: [], picks: records.picks };
244
+ const filtered = kindAsk(words);
245
+ if (filtered)
246
+ return filtered;
247
+ /*
248
+ * A kind this seat sees, named with words that are not a filter, is a
249
+ * kind to go to when nothing else is said ("go to the tasks"), and an
250
+ * ask for something else — a drawing, a change — otherwise. Only a name
251
+ * that is nothing this seat can see is "nothing by that name".
252
+ */
253
+ const kind = kindIn(words);
254
+ if (kind) {
255
+ if (kind.rest.split(" ").every((word) => word === "" || FILLER.has(word))) {
256
+ const title = pluralOf(kind.kind);
257
+ const move = { to: "kind", kind: kind.kind, title, address: listAddress(kind.kind), said: `Went to the ${title.toLowerCase()}.` };
258
+ return { about: "kind", say: move.said, moves: [move] };
259
+ }
260
+ return { unresolved: true };
261
+ }
262
+ return nothing();
263
+ };
264
+ /** What a place is, in a line: what it draws and how many. */
265
+ const describePlace = (place) => {
266
+ if (place.kind === null) {
267
+ const counts = visibleKinds
268
+ .map((kind) => ({ kind, count: graph.nodesOfKind(kind).length }))
269
+ .filter((one) => one.count > 0)
270
+ .map((one) => `${one.count} ${(one.count === 1 ? nounOf(definitionOf(one.kind), one.kind) : pluralOf(one.kind)).toLowerCase()}`);
271
+ const problems = seen.violations().length;
272
+ return [counts.length > 0 ? `It holds ${list(counts)}.` : "It holds nothing yet.", problems > 0 ? `${problems === 1 ? "One problem" : `${problems} problems`} to see to.` : ""].filter(Boolean).join(" ");
273
+ }
274
+ const count = graph.nodesOfKind(place.kind).length;
275
+ const plural = pluralOf(place.kind).toLowerCase();
276
+ const flagged = new Set(seen.violations().flatMap((violation) => violation.nodeIds));
277
+ const troubled = graph.nodesOfKind(place.kind).filter((node) => flagged.has(node.id)).length;
278
+ return [
279
+ place.lens ? `It draws the ${plural} as ${withArticle(place.lens)}${count > 0 ? ` — ${count} of them` : ""}.` : `${count === 0 ? "No" : count} ${count === 1 ? nounOf(definitionOf(place.kind), place.kind) : plural} ${count === 1 ? "is" : "are"} here.`,
280
+ troubled > 0 ? `${troubled} ${troubled === 1 ? "has" : "have"} a problem.` : "",
281
+ ]
282
+ .filter(Boolean)
283
+ .join(" ");
284
+ };
285
+ /** "What is here": the selection, else the place the reader stands in, else the home. */
286
+ const here = () => {
287
+ const selected = (context.selection ?? []).map((id) => graph.getNode(id)).find((node) => node !== undefined);
288
+ if (selected)
289
+ return { about: "here", say: describeRecord(selected), moves: [], subject: selected.id };
290
+ const standing = places.find((place) => place.slug === context.place) ?? places.find((place) => place.slug === "home");
291
+ if (standing)
292
+ return { about: "here", say: `${standing.title}. ${describePlace(standing)}`, moves: [], subject: standing.slug };
293
+ return { about: "here", say: describePlace({ slug: "home", title: "Home", kind: null, cardinality: "many", address: "/", stop: "#" }), moves: [] };
294
+ };
295
+ /* ---------------------------------------------- 3. a kind, narrowed */
296
+ /** The kind a run of words names, by its plural or its noun, and the words left over. */
297
+ const kindIn = (words) => {
298
+ const candidates = visibleKinds
299
+ .flatMap((kind) => [pluralOf(kind), nounOf(definitionOf(kind), kind), kind].map((name) => ({ kind, name: fold(name) })))
300
+ .filter((one) => one.name.length > 0)
301
+ .sort((a, b) => b.name.length - a.name.length);
302
+ for (const { kind, name } of candidates) {
303
+ const at = ` ${words} `.indexOf(` ${name} `);
304
+ if (at < 0)
305
+ continue;
306
+ return { kind, rest: ` ${words} `.replace(` ${name} `, " ").replace(/\s+/g, " ").trim() };
307
+ }
308
+ return undefined;
309
+ };
310
+ /** The date field an ask reads: the one its words name, a date role, or the kind's only date. */
311
+ const dateFieldOf = (kind, words) => {
312
+ const dates = arrangeable(schema, kind).filters.filter((offer) => offer.about === "field" && offer.type === "date");
313
+ if (dates.length === 0)
314
+ return undefined;
315
+ const named = dates.find((offer) => words.some((word) => fold(offer.key) === word || fold(offer.label) === word));
316
+ if (named)
317
+ return named;
318
+ const roles = (definitionOf(kind)?.fieldRoles ?? {});
319
+ for (const role of ["due", "deadline", "date", "when", "start", "end"]) {
320
+ const field = roles[role];
321
+ const offer = field ? dates.find((one) => one.key === field) : undefined;
322
+ if (offer)
323
+ return offer;
324
+ }
325
+ const byName = dates.find((offer) => ["due", "deadline", "date", "when", "on", "at"].includes(offer.key.toLowerCase()));
326
+ return byName ?? (dates.length === 1 ? dates[0] : undefined);
327
+ };
328
+ /** "Not finished", in the arrangement's words when it can be said; undefined when it cannot. */
329
+ const unfinishedOf = (kind) => {
330
+ const definition = definitionOf(kind);
331
+ const offers = arrangeable(schema, kind).filters;
332
+ const lifecycle = definition?.lifecycle;
333
+ if (lifecycle) {
334
+ return { conditions: [{ key: "is", value: "current" }], holds: (node) => conditionHolds(ctx, node, { key: "is", value: "current" }) };
335
+ }
336
+ const finished = offers.find((offer) => offer.about === "field" && offer.type === "boolean" && FINISHED.has(fold(offer.key)));
337
+ if (finished) {
338
+ return { conditions: [{ key: finished.key, value: "false" }], holds: (node) => node[finished.key] !== true };
339
+ }
340
+ const status = offers.find((offer) => offer.about === "field" && offer.type === "choice" && (offer.options ?? []).some((option) => FINISHED.has(fold(option))));
341
+ if (status) {
342
+ const done = new Set((status.options ?? []).filter((option) => FINISHED.has(fold(option))));
343
+ const open = (status.options ?? []).filter((option) => !done.has(option));
344
+ // One value left that is not finished is a condition the words can carry; several is not.
345
+ if (open.length === 1)
346
+ return { conditions: [{ key: status.key, value: open[0] }], holds: (node) => node[status.key] === open[0] };
347
+ return "unsayable";
348
+ }
349
+ return { conditions: [], holds: () => true };
350
+ };
351
+ /**
352
+ * A date ask in a reader's words, against the field it reads: "due Friday
353
+ * 4 Sep", "on Thursday 17 Sep", "sown this week". A field that only means
354
+ * "when" ("Date", "Day") says nothing a reader needs: "shifts this week",
355
+ * not "shifts date this week".
356
+ */
357
+ const whenWords = (ask, field) => {
358
+ const due = ask.words.startsWith("due") || fold(field.key) === "due";
359
+ const plain = JUST_WHEN.test(fold(field.label));
360
+ if (ask.day)
361
+ return due ? `due ${ask.day}` : plain ? `on ${ask.day}` : `${field.label.toLowerCase()} on ${ask.day}`;
362
+ const when = ask.words.replace(/^(?:due|for|on|by) (?:the )?/, "");
363
+ return due ? `due ${when}` : plain ? when : `${field.label.toLowerCase()} ${when}`;
364
+ };
365
+ const flaggedIds = new Set(seen.violations().flatMap((violation) => violation.nodeIds));
366
+ const ctx = { schema, graph: seen.graph, flagged: flaggedIds, today };
367
+ /** A kind with a date, a status or a yes/no — "deliverables due this week", "open decisions", "done tasks". */
368
+ const kindAsk = (words) => {
369
+ const dated = readDate(words, today, weekStartsOn);
370
+ const named = kindIn(dated?.rest ?? words);
371
+ let kind = named?.kind;
372
+ let rest = (named?.rest ?? dated?.rest ?? words).split(" ").filter(Boolean);
373
+ if (!kind && dated) {
374
+ /*
375
+ * "What's due this week": the one kind that carries a date the words
376
+ * can read — and among several, the one whose date the words name
377
+ * ("due" is a task's `due`, not a rule's start of effect).
378
+ */
379
+ const said = words.split(" ");
380
+ const carrying = visibleKinds.filter((one) => dateFieldOf(one, said) !== undefined);
381
+ const naming = carrying.filter((one) => {
382
+ const field = dateFieldOf(one, said);
383
+ return said.some((word) => fold(field.key) === word || fold(field.label) === word);
384
+ });
385
+ const only = carrying.length === 1 ? carrying : naming;
386
+ if (only.length !== 1)
387
+ return undefined;
388
+ kind = only[0];
389
+ }
390
+ if (!kind)
391
+ return undefined;
392
+ const offers = arrangeable(schema, kind).filters;
393
+ const conditions = [];
394
+ /* How it is said: "overdue tasks", "open decisions", "tasks due this week". */
395
+ const phrases = [];
396
+ const after = [];
397
+ const holds = [];
398
+ let unsayable = false;
399
+ // A choice's own value: "open decisions", "growing plantings".
400
+ const leftover = [];
401
+ for (let at = 0; at < rest.length; at++) {
402
+ const word = rest[at];
403
+ const negated = at > 0 && (rest[at - 1] === "not" || rest[at - 1] === "un");
404
+ const choice = offers.find((offer) => offer.about === "field" && offer.type === "choice" && (offer.options ?? []).some((option) => fold(option) === word));
405
+ if (choice && !negated) {
406
+ const value = (choice.options ?? []).find((option) => fold(option) === word);
407
+ conditions.push({ key: choice.key, value });
408
+ phrases.push(value);
409
+ continue;
410
+ }
411
+ // A yes/no by its name or its label: "done tasks", "unfinished tasks", "tasks not done".
412
+ const flag = offers.find((offer) => offer.about === "field" && offer.type === "boolean" && [fold(offer.key), fold(offer.label)].some((name) => name === word || name === word.replace(/^un/, "")));
413
+ if (flag) {
414
+ const yes = !negated && !(word.startsWith("un") && !fold(flag.key).startsWith("un"));
415
+ conditions.push({ key: flag.key, value: String(yes) });
416
+ phrases.push(yes ? word : `not ${word.replace(/^un/, "")}`);
417
+ continue;
418
+ }
419
+ if (OPEN_WORDS.has(word) && !negated) {
420
+ const open = unfinishedOf(kind);
421
+ if (open === "unsayable") {
422
+ unsayable = true;
423
+ holds.push((node) => !finishedNode(schema, node));
424
+ }
425
+ else {
426
+ conditions.push(...open.conditions);
427
+ holds.push(open.holds);
428
+ }
429
+ phrases.push(word);
430
+ continue;
431
+ }
432
+ if (word === "not" || word === "un")
433
+ continue;
434
+ // The date the words name ("sown this week") is read with the date, below.
435
+ if (dated && offers.some((offer) => offer.type === "date" && (fold(offer.key) === word || fold(offer.label) === word)))
436
+ continue;
437
+ leftover.push(word);
438
+ }
439
+ rest = leftover;
440
+ // Anything still unread is a sentence this is not.
441
+ if (rest.some((word) => !FILLER.has(word)))
442
+ return undefined;
443
+ if (!dated && conditions.length === 0 && holds.length === 0)
444
+ return undefined;
445
+ const plural = pluralOf(kind).toLowerCase();
446
+ const title = pluralOf(kind);
447
+ if (dated) {
448
+ const field = dateFieldOf(kind, words.split(" "));
449
+ if (!field) {
450
+ const move = { to: "kind", kind, title, address: listAddress(kind), said: `Went to the ${plural}.` };
451
+ return {
452
+ about: "kind",
453
+ say: `${capitalize(title)} carry no date, so I can't tell which are ${/^(?:due|for|on|overdue|past due|late)\b/.test(dated.ask.words) ? dated.ask.words : `due ${dated.ask.words}`}. ${move.said}`,
454
+ moves: [move],
455
+ };
456
+ }
457
+ if (dated.ask.from)
458
+ conditions.push({ key: field.key, value: `after:${addDays(dated.ask.from, -1)}` });
459
+ if (dated.ask.to)
460
+ conditions.push({ key: field.key, value: `before:${addDays(dated.ask.to, 1)}` });
461
+ if (dated.ask.overdue) {
462
+ const open = unfinishedOf(kind);
463
+ if (open === "unsayable") {
464
+ unsayable = true;
465
+ holds.push((node) => !finishedNode(schema, node));
466
+ }
467
+ else {
468
+ conditions.push(...open.conditions);
469
+ holds.push(open.holds);
470
+ }
471
+ }
472
+ if (dated.ask.overdue)
473
+ phrases.push("overdue");
474
+ else
475
+ after.push(whenWords(dated.ask, field));
476
+ }
477
+ const members = graph
478
+ .nodesOfKind(kind)
479
+ .filter((node) => conditions.every((condition) => conditionHolds(ctx, node, condition)) && holds.every((one) => one(node)));
480
+ const words2 = [...phrases, ...after].join(" and ");
481
+ const said = [...phrases, plural, ...after].join(" ");
482
+ const picks = members.slice(0, 6).map((node) => ({
483
+ about: "node",
484
+ id: node.id,
485
+ kind,
486
+ label: nameOf(node),
487
+ why: { field: conditions[0]?.key ?? "label", reading: conditions[0]?.key ?? "Name", fragment: words2, strength: "field" },
488
+ current: true,
489
+ flagged: flaggedIds.has(node.id),
490
+ address: recordAddress(node),
491
+ }));
492
+ const counted = members.length === 0 ? `No ${plural} are ${words2}.` : `${members.length === 1 ? `One ${nounOf(definitionOf(kind), kind)} is` : `${members.length} ${plural} are`} ${words2}: ${list(members.slice(0, 6).map(nameOf))}${members.length > 6 ? `, and ${members.length - 6} more` : ""}.`;
493
+ if (unsayable) {
494
+ // The list cannot be narrowed to exactly these: say them, and offer a picture of them.
495
+ return { about: "kind", say: counted, moves: [], picks, offer: { draft: said, label: "Show as a view" } };
496
+ }
497
+ const filter = conditions.map((condition) => `${condition.key}:${condition.value}`).join(",");
498
+ const address = `${listAddress(kind)}?${new URLSearchParams({ filter }).toString()}`;
499
+ const move = { to: "kind", kind, title: capitalize(said), filter, address, said: `Went to the ${said}.` };
500
+ return { about: "kind", say: `${move.said} ${counted}`, moves: [move], picks };
501
+ };
502
+ /* ------------------------------------- 3b. who, across one relation */
503
+ /** Whether a kind is somebody: drawn as a person, or named as one. */
504
+ const personLike = (kind) => {
505
+ const definition = definitionOf(kind);
506
+ if (definition?.figure === "person")
507
+ return true;
508
+ return [kind, nounOf(definitionOf(kind), kind), pluralOf(kind)].some((name) => fold(name).split(" ").some((word) => PEOPLE.has(word)));
509
+ };
510
+ /** Every relation one kind has, from the end it stands on: to whom, and in whose words. */
511
+ const relationsOf = (kind) => {
512
+ const out = [];
513
+ const edges = (of) => (definitionOf(of)?.edges ?? {});
514
+ for (const [key, edge] of Object.entries(edges(kind))) {
515
+ for (const far of edge.to ?? [])
516
+ if (visible.has(far))
517
+ out.push({ key, direction: "out", far, words: stems(`${edge.description ?? ""} ${key}`) });
518
+ }
519
+ for (const other of visibleKinds) {
520
+ for (const [key, edge] of Object.entries(edges(other))) {
521
+ if ((edge.to ?? []).includes(kind))
522
+ out.push({ key, direction: "in", far: other, words: stems(`${edge.inverse ?? ""} ${key}`) });
523
+ }
524
+ }
525
+ return out;
526
+ };
527
+ /**
528
+ * "Who's working thursday", "which plots were planted this week": the
529
+ * records of a kind on a date, and the records one relation ties them
530
+ * to — the people when the ask is "who", the kind it names otherwise.
531
+ * The relation is the one whose declared words say what the ask says
532
+ * ("working" is "who is covering it"); with no verb ("who's on
533
+ * tuesday"), the only one that reaches the kind asked for.
534
+ */
535
+ const whoAsk = (words) => {
536
+ const asking = words.match(/^(who|which|what)\b/)?.[1];
537
+ if (!asking)
538
+ return undefined;
539
+ const dated = readDate(words, today, weekStartsOn);
540
+ if (!dated || dated.ask.overdue)
541
+ return undefined;
542
+ const said = dated.rest.split(" ").filter(Boolean);
543
+ // The kinds the words name, longest name first: the kind asked for, and perhaps the kind filtered.
544
+ const kindNames = visibleKinds
545
+ .flatMap((kind) => [pluralOf(kind), nounOf(definitionOf(kind), kind), kind].map((name) => ({ kind, name: fold(name) })))
546
+ .filter((one) => one.name.length > 0)
547
+ .sort((a, b) => b.name.length - a.name.length);
548
+ let rest = ` ${said.join(" ")} `;
549
+ const named = [];
550
+ for (const { kind, name } of kindNames) {
551
+ if (!rest.includes(` ${name} `))
552
+ continue;
553
+ rest = rest.replace(` ${name} `, " ");
554
+ if (!named.includes(kind))
555
+ named.push(kind);
556
+ }
557
+ const auxiliary = rest.match(/\b(?:is|are|was|were)\b|'s\b/)?.[0];
558
+ const verbs = rest
559
+ .replace(/'s\b/g, " ")
560
+ .split(" ")
561
+ .filter((word) => word.length > 0 && !FILLER.has(word) && !ASKING.has(word));
562
+ const target = asking === "who" ? named.find(personLike) : named[0];
563
+ if (!target && asking !== "who")
564
+ return undefined;
565
+ const filteredNamed = named.find((kind) => kind !== target);
566
+ /* Every (filtered kind, relation) the ask could mean, scored by how plainly it says it. */
567
+ const verbStems = verbs.flatMap((verb) => [stem(verb), ...(SAME_WORK.has(stem(verb)) ? [...SAME_WORK] : [])]);
568
+ const readings = visibleKinds
569
+ .filter((kind) => (filteredNamed ? kind === filteredNamed : kind !== target))
570
+ .flatMap((kind) => {
571
+ // A kind with several dates and none named: its first, which is when it happened ("planted" is when it was sown).
572
+ const field = dateFieldOf(kind, words.split(" ")) ?? arrangeable(schema, kind).filters.find((offer) => offer.about === "field" && offer.type === "date");
573
+ if (!field)
574
+ return [];
575
+ return relationsOf(kind)
576
+ .filter((relation) => (target ? relation.far === target : personLike(relation.far)) && relation.far !== kind)
577
+ .map((relation) => ({ kind, field, relation, said: verbs.length === 0 || verbStems.some((verb) => relation.words.some((word) => sameStem(word, verb))) }));
578
+ })
579
+ .filter((reading) => reading.said);
580
+ if (readings.length === 0)
581
+ return undefined;
582
+ // Among several, the one whose date the words name; else it is not plain which was meant.
583
+ const naming = readings.filter((reading) => said.some((word) => fold(reading.field.key) === word || fold(reading.field.label) === word));
584
+ const chosen = readings.length === 1 ? readings[0] : naming.length === 1 ? naming[0] : undefined;
585
+ if (!chosen)
586
+ return undefined;
587
+ const { kind, field, relation } = chosen;
588
+ const conditions = [
589
+ ...(dated.ask.from ? [{ key: field.key, value: `after:${addDays(dated.ask.from, -1)}` }] : []),
590
+ ...(dated.ask.to ? [{ key: field.key, value: `before:${addDays(dated.ask.to, 1)}` }] : []),
591
+ ];
592
+ const members = graph.nodesOfKind(kind).filter((node) => conditions.every((condition) => conditionHolds(ctx, node, condition)));
593
+ const reach = (node) => (relation.direction === "out" ? seen.graph.out(node.id, relation.key) : seen.graph.in(node.id, relation.key)).filter((far) => far.kind === relation.far && visible.has(relation.far));
594
+ const found = [];
595
+ const nobody = [];
596
+ for (const node of members) {
597
+ const tied = reach(node);
598
+ if (tied.length === 0)
599
+ nobody.push(node);
600
+ for (const far of tied)
601
+ if (!found.some((held) => held.id === far.id))
602
+ found.push(far);
603
+ }
604
+ const when = whenWords(dated.ask, field);
605
+ const lead = dated.ask.day ? `On ${dated.ask.day}` : capitalize(dated.ask.words.replace(/^(?:due|for|on|by) (?:the )?/, ""));
606
+ const plural = pluralOf(kind).toLowerCase();
607
+ const filter = conditions.map((condition) => `${condition.key}:${condition.value}`).join(",");
608
+ const title = `${plural} ${when}`;
609
+ const move = { to: "kind", kind, title: capitalize(title), filter, address: `${listAddress(kind)}?${new URLSearchParams({ filter }).toString()}`, said: `Went to the ${title}.` };
610
+ if (members.length === 0)
611
+ return { about: "related", say: `No ${title}. ${move.said}`, moves: [move] };
612
+ const verb = verbs.join(" ");
613
+ const past = auxiliary === "was" || auxiliary === "were";
614
+ const be = (count) => (past ? (count === 1 ? "was" : "were") : count === 1 ? "is" : "are");
615
+ const names = found.map(nameOf);
616
+ const shown = names.length > 8 ? [...names.slice(0, 8), `${names.length - 8} more`] : names;
617
+ const answer = found.length === 0
618
+ ? `${lead}: nobody ${be(1)}${verb ? ` ${verb}` : ""}.`
619
+ : `${lead}: ${list(shown)}${verb ? ` ${be(found.length)} ${verb}` : ""}.`;
620
+ // What has nobody tied to it is said too, when the ask is about people: the gap is the news.
621
+ const gaps = asking === "who" && nobody.length > 0 ? `${list(nobody.slice(0, 4).map(nameOf))}${nobody.length > 4 ? ` and ${nobody.length - 4} more` : ""} ${nobody.length === 1 ? "has" : "have"} nobody.` : "";
622
+ const picks = found.slice(0, 8).map((node) => ({
623
+ about: "node",
624
+ id: node.id,
625
+ kind: node.kind,
626
+ label: nameOf(node),
627
+ why: { field: relation.key, reading: edgeWords(schema, relation.direction === "out" ? kind : relation.far, relation.key, relation.direction === "out" ? "out" : "in"), fragment: when, strength: "field" },
628
+ current: true,
629
+ flagged: flaggedIds.has(node.id),
630
+ address: recordAddress(node),
631
+ }));
632
+ return { about: "related", say: [answer, gaps, move.said].filter(Boolean).join(" "), moves: [move], picks };
633
+ };
634
+ /* ------------------------------------------------------- in order */
635
+ // 4. What's wrong — with the whole, or with one thing.
636
+ const wrong = asked.match(WRONG);
637
+ if (wrong) {
638
+ const about = wrong[1];
639
+ if (about && !HERE_WORDS.has(about) && !/^(?:it|this|that)$/.test(about)) {
640
+ const place = placeNamed(about);
641
+ const records = place ? undefined : recordsNamed(stripThe(about) || about);
642
+ if (records?.one) {
643
+ const move = toRecord(records.one);
644
+ return { about: "describe", say: `${move.said} ${describeRecord(records.one)}`, moves: [move], subject: records.one.id };
645
+ }
646
+ if (!place)
647
+ return records && records.picks.length > 0 ? { about: "picks", say: picksSaid(records.picks), moves: [], picks: records.picks } : nothing();
648
+ }
649
+ if (about && /^(?:it|this|that)$|^(?:here|this place|this page)$/.test(about)) {
650
+ const selected = (context.selection ?? []).map((id) => graph.getNode(id)).find((node) => node !== undefined);
651
+ if (selected)
652
+ return { about: "describe", say: describeRecord(selected), moves: [], subject: selected.id };
653
+ }
654
+ const violations = seen.violations();
655
+ if (violations.length === 0)
656
+ return { about: "problems", say: "Nothing is wrong — every rule holds.", moves: [] };
657
+ const move = { to: "problems", address: "/problems", said: "Went to the problems." };
658
+ return {
659
+ about: "problems",
660
+ say: `${move.said} ${brokenWords(violations)}: ${violations
661
+ .slice(0, 4)
662
+ .map((violation) => violation.message)
663
+ .join("; ")}${violations.length > 4 ? "…" : "."}`,
664
+ moves: [move],
665
+ };
666
+ }
667
+ // 5a. What is here.
668
+ if (HERE.test(asked))
669
+ return here();
670
+ // 3b. Who, on a day, across one relation: "who's working thursday".
671
+ const who = whoAsk(asked);
672
+ if (who)
673
+ return who;
674
+ /*
675
+ * A day and nothing else — "what's on thursday", "what's due friday" —
676
+ * is the records on that day, unless the day's words are a place's name
677
+ * ("This week" can be a list of its own).
678
+ */
679
+ const onlyDate = readDate(asked, today, weekStartsOn);
680
+ if (onlyDate && !placeNamed(stripThe(onlyDate.ask.words)) && onlyDate.rest.replace(/'s\b/g, "").split(" ").every((word) => word === "" || FILLER.has(word) || ASKING.has(word))) {
681
+ const dated = kindAsk(asked);
682
+ if (dated)
683
+ return dated;
684
+ }
685
+ // 1, 2. Go to a place or a record by name.
686
+ /*
687
+ * "Open decisions" is the decisions still open, not the decisions'
688
+ * list opened: where "open" reads as a filter on a kind, it is one.
689
+ */
690
+ if (/^open /.test(asked)) {
691
+ const filtered = kindAsk(asked);
692
+ if (filtered)
693
+ return filtered;
694
+ }
695
+ const go = asked.match(GO) ?? asked.match(/^(?:go|take me|head|get me)(?: back)? (home)$/);
696
+ if (go)
697
+ return goNamed(go[1].trim(), false);
698
+ // 5b. Tell me about a place or a record.
699
+ const tell = asked.match(TELL);
700
+ if (tell) {
701
+ const told = goNamed(tell[1].trim(), true);
702
+ // A question that names nothing by name is not refused here: it may be one a model can answer.
703
+ return "unresolved" in told && told.unresolved && !/^tell me|^describe/.test(asked) ? { unresolved: true } : told;
704
+ }
705
+ // A bare place or a bare name is a place to go.
706
+ const place = placeNamed(asked);
707
+ if (place) {
708
+ const move = toPlace(place);
709
+ return { about: "place", say: move.said, moves: [move], subject: place.slug };
710
+ }
711
+ // 3. A kind with a date or a status.
712
+ const filtered = kindAsk(asked);
713
+ if (filtered)
714
+ return filtered;
715
+ return { unresolved: true };
716
+ }
717
+ /** The words that ask for somebody or something across a relation. */
718
+ const ASKING = new Set(["who", "whom", "whose", "which", "what", "whats", "what's", "who's"]);
719
+ /** Words a kind of somebody is named with: a "who" is one of these. */
720
+ const PEOPLE = new Set([
721
+ "person", "people", "user", "users", "member", "members", "volunteer", "volunteers", "gardener", "gardeners", "player", "players",
722
+ "staff", "worker", "workers", "employee", "employees", "owner", "owners", "assignee", "assignees", "helper", "helpers", "student",
723
+ "students", "teacher", "teachers", "customer", "customers", "client", "clients", "contact", "contacts", "author", "authors",
724
+ ]);
725
+ /**
726
+ * Being there for something, said several ways: "working" a shift is
727
+ * "covering" it, "staffing" it, being "on" it. Only these are read as the
728
+ * same; every other verb must match the relation's own words.
729
+ */
730
+ const SAME_WORK = new Set(["work", "cover", "staff", "assign", "do", "run", "schedul", "roster", "book", "duty", "serv", "help"]);
731
+ /** A word without its ending, so "covering", "covered" and "covers" are one word. */
732
+ function stem(word) {
733
+ const bare = word.toLowerCase().replace(/'s$/, "");
734
+ for (const ending of ["ing", "ed", "es", "s"]) {
735
+ if (bare.length > ending.length + 2 && bare.endsWith(ending)) {
736
+ const cut = bare.slice(0, -ending.length);
737
+ // "planned" → "plan", "running" → "run".
738
+ return cut.length > 3 && cut[cut.length - 1] === cut[cut.length - 2] ? cut.slice(0, -1) : cut;
739
+ }
740
+ }
741
+ return bare;
742
+ }
743
+ /** The stems of a relation's words, the small words dropped. */
744
+ function stems(text) {
745
+ return text
746
+ .toLowerCase()
747
+ .split(/[^a-z']+/)
748
+ .filter((word) => word.length > 1 && !FILLER.has(word) && !ASKING.has(word) && !["it", "they", "them", "their", "its", "this", "here", "to", "at"].includes(word))
749
+ .map(stem);
750
+ }
751
+ const sameStem = (a, b) => a === b || (a.length >= 4 && b.length >= 4 && (a.startsWith(b) || b.startsWith(a)));
752
+ /** Finished, read by the words a status or a yes/no usually uses for it. */
753
+ const FINISHED = new Set(["done", "finished", "complete", "completed", "closed", "resolved", "agreed", "canceled", "archived", "shipped", "delivered"]);
754
+ /** Words that ask for what is not finished. */
755
+ const OPEN_WORDS = new Set(["open", "unfinished", "outstanding", "pending", "remaining", "undone", "incomplete"]);
756
+ function finishedNode(schema, node) {
757
+ const offers = arrangeable(schema, node.kind).filters;
758
+ return offers.some((offer) => offer.about === "field" &&
759
+ ((offer.type === "boolean" && FINISHED.has(offer.key.toLowerCase()) && node[offer.key] === true) ||
760
+ (offer.type === "choice" && typeof node[offer.key] === "string" && FINISHED.has(String(node[offer.key]).toLowerCase()))));
761
+ }
762
+ /** "A, B and C". */
763
+ function list(items) {
764
+ return items.length <= 1 ? (items[0] ?? "") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
765
+ }
766
+ /**
767
+ * THE PLACES, FROM WHAT A FACE HOLDS: the schema and the places its view
768
+ * registry names (a declared lens registers one). The same list `placesOf`
769
+ * makes from the declaration — the home, the scene, each picture, each
770
+ * kind's list, with the same addresses — for a seat that is handed a store
771
+ * and its views rather than the app.
772
+ */
773
+ export function placesFromViews(schema, places, options = {}) {
774
+ // The scene's word, said outright, stands over the arrangement's.
775
+ const pages = options.scene !== undefined ? { ...options.pages, scene: options.scene } : options.pages;
776
+ return [...placesFrom(schema, places, pages ? { pages } : {})].map(({ first: _first, hidden: _hidden, lens: _lens, ...place }) => place);
777
+ }
778
+ /** What the resolver is handed from a turn's context. */
779
+ export function askContextOf(context, today) {
780
+ return {
781
+ ...(context.principal ? { principal: context.principal } : {}),
782
+ ...(context.places ? { places: context.places } : {}),
783
+ ...(context.selection ? { selection: context.selection } : {}),
784
+ ...(context.place ? { place: context.place } : {}),
785
+ ...((today ?? context.today) ? { today: today ?? context.today } : {}),
786
+ ...(context.weekStartsOn !== undefined ? { weekStartsOn: context.weekStartsOn } : {}),
787
+ };
788
+ }
789
+ /**
790
+ * AN ASK, AS THE GRAPH RESPONDER TAKES IT: a whole reply when the moves are
791
+ * the answer; otherwise the moves to carry, and whether the fuller answer
792
+ * the responder already gives — the problems with their repairs, a record
793
+ * with its relations — is the one meant.
794
+ */
795
+ export function goingFrom(store, text, context, today) {
796
+ const answer = resolveAsk(store, text, askContextOf(context, today));
797
+ if (answer.unresolved)
798
+ return answer.say ? { reply: { say: answer.say, proposals: [], grounded: true } } : {};
799
+ if (answer.about === "picks")
800
+ return {};
801
+ const moves = answer.moves.length > 0 ? { moves: answer.moves } : {};
802
+ const subject = answer.subject ? store.graph.getNode(answer.subject) : undefined;
803
+ if (answer.about === "problems")
804
+ return { ...moves, problems: true };
805
+ if (subject && (answer.about === "describe" || answer.about === "here"))
806
+ return { ...moves, told: subject.id };
807
+ const proposals = subject ? validateProposals(store, readyRepairsOf(violationsTouching(store.violations(), [subject.id])).slice(0, 3)) : [];
808
+ return {
809
+ reply: {
810
+ say: answer.say,
811
+ proposals,
812
+ grounded: true,
813
+ ...moves,
814
+ ...(answer.picks && answer.picks.length > 0 ? { picks: answer.picks } : {}),
815
+ ...(answer.offer ? { offer: answer.offer } : {}),
816
+ },
817
+ };
818
+ }
819
+ /**
820
+ * Keeps the moves a model proposed that the seat can make: each is read
821
+ * again as an ask ("go to <it>") under the same sight, so a model can only
822
+ * ever move the app to a place or a record the resolver itself would.
823
+ */
824
+ export function movesFromNames(store, names, given = {}) {
825
+ const context = askContextOf(given);
826
+ const out = [];
827
+ for (const name of names) {
828
+ const words = typeof name === "string" ? name : typeof name === "object" && name !== null && typeof name.to === "string" ? name.to : undefined;
829
+ if (!words || words.trim().length === 0)
830
+ continue;
831
+ const answer = resolveAsk(store, /^(?:go|take me|open|show)\b/i.test(words.trim()) ? words : `go to ${words}`, context);
832
+ if ("moves" in answer)
833
+ for (const move of answer.moves)
834
+ if (!out.some((held) => held.address === move.address))
835
+ out.push(move);
836
+ }
837
+ return out;
838
+ }
839
+ //# sourceMappingURL=go.js.map