@graview/tools 0.1.64 → 0.1.66

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 (79) hide show
  1. package/dist/ai.d.ts +56 -1
  2. package/dist/ai.d.ts.map +1 -1
  3. package/dist/ai.js.map +1 -1
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +2 -1
  6. package/dist/cli.js.map +1 -1
  7. package/dist/design-agent.d.ts +140 -0
  8. package/dist/design-agent.d.ts.map +1 -0
  9. package/dist/design-agent.js +234 -0
  10. package/dist/design-agent.js.map +1 -0
  11. package/dist/dev-ai.d.ts +4 -0
  12. package/dist/dev-ai.d.ts.map +1 -1
  13. package/dist/dev-ai.js +165 -8
  14. package/dist/dev-ai.js.map +1 -1
  15. package/dist/draft-check.d.ts +108 -0
  16. package/dist/draft-check.d.ts.map +1 -0
  17. package/dist/draft-check.js +296 -0
  18. package/dist/draft-check.js.map +1 -0
  19. package/dist/draft.d.ts +1 -0
  20. package/dist/draft.d.ts.map +1 -1
  21. package/dist/draft.js +2 -0
  22. package/dist/draft.js.map +1 -1
  23. package/dist/facts.d.ts +24 -0
  24. package/dist/facts.d.ts.map +1 -0
  25. package/dist/facts.js +48 -0
  26. package/dist/facts.js.map +1 -0
  27. package/dist/frame.d.ts +1 -1
  28. package/dist/frame.d.ts.map +1 -1
  29. package/dist/graph-plan.d.ts +178 -0
  30. package/dist/graph-plan.d.ts.map +1 -0
  31. package/dist/graph-plan.js +570 -0
  32. package/dist/graph-plan.js.map +1 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/inline-ai.d.ts +41 -2
  36. package/dist/inline-ai.d.ts.map +1 -1
  37. package/dist/inline-ai.js +441 -12
  38. package/dist/inline-ai.js.map +1 -1
  39. package/dist/page-better.d.ts +240 -0
  40. package/dist/page-better.d.ts.map +1 -0
  41. package/dist/page-better.js +383 -0
  42. package/dist/page-better.js.map +1 -0
  43. package/dist/providers/structure.d.ts.map +1 -1
  44. package/dist/providers/structure.js +2 -2
  45. package/dist/providers/structure.js.map +1 -1
  46. package/dist/reshape.d.ts +70 -2
  47. package/dist/reshape.d.ts.map +1 -1
  48. package/dist/reshape.js +2 -0
  49. package/dist/reshape.js.map +1 -1
  50. package/dist/say-change.d.ts +59 -0
  51. package/dist/say-change.d.ts.map +1 -0
  52. package/dist/say-change.js +156 -0
  53. package/dist/say-change.js.map +1 -0
  54. package/dist/section.d.ts +146 -0
  55. package/dist/section.d.ts.map +1 -0
  56. package/dist/section.js +379 -0
  57. package/dist/section.js.map +1 -0
  58. package/dist/sentences.d.ts +13 -0
  59. package/dist/sentences.d.ts.map +1 -0
  60. package/dist/sentences.js +30 -0
  61. package/dist/sentences.js.map +1 -0
  62. package/dist/suggest.js +2 -2
  63. package/dist/suggest.js.map +1 -1
  64. package/dist/tidy/blocking.d.ts.map +1 -1
  65. package/dist/tidy/blocking.js +11 -9
  66. package/dist/tidy/blocking.js.map +1 -1
  67. package/dist/tidy/judges.d.ts +19 -0
  68. package/dist/tidy/judges.d.ts.map +1 -1
  69. package/dist/tidy/judges.js +46 -8
  70. package/dist/tidy/judges.js.map +1 -1
  71. package/dist/tidy/judging.d.ts.map +1 -1
  72. package/dist/tidy/judging.js +15 -24
  73. package/dist/tidy/judging.js.map +1 -1
  74. package/dist/workflows/run-classify.js +4 -4
  75. package/dist/workflows/run-classify.js.map +1 -1
  76. package/dist/workflows/run.d.ts.map +1 -1
  77. package/dist/workflows/run.js +2 -1
  78. package/dist/workflows/run.js.map +1 -1
  79. package/package.json +7 -3
@@ -0,0 +1,570 @@
1
+ import { argumentsTaken, labelOf, nodeRefArgs, pluralOf, withArticle } from "@graview/core";
2
+ /** How sure the Fast slot must be to stand without the Thinking slot, and how sure before a reading goes unsaid. */
3
+ export const GRAPH_SURE = 0.6;
4
+ export const READING_SURE = 0.75;
5
+ const PEOPLE = new Set(["person", "people", "user", "users", "member", "members", "volunteer", "volunteers", "staff", "contact", "contacts", "employee", "employees", "client", "clients", "customer", "customers", "guest", "guests", "player", "players", "student", "students"]);
6
+ const capital = (words) => words.charAt(0).toUpperCase() + words.slice(1);
7
+ /** Verbs that give a record to someone. */
8
+ const GIVING = { assign: true, reassign: true, give: true, hand: true, delegate: true, allocate: true };
9
+ /** The record a target holds others of: the biggest group of records linked to it, of one kind other than its own. */
10
+ export function heldBy(store, id) {
11
+ const self = store.graph.getNode(id);
12
+ if (!self)
13
+ return undefined;
14
+ const groups = new Map();
15
+ for (const node of [...store.graph.in(id), ...store.graph.out(id)]) {
16
+ if (node.kind === self.kind)
17
+ continue;
18
+ groups.set(node.kind, [...new Set([...(groups.get(node.kind) ?? []), node.id])]);
19
+ }
20
+ const biggest = [...groups.entries()].sort((a, b) => b[1].length - a[1].length)[0];
21
+ return biggest && biggest[1].length > 1 ? { kind: biggest[0], ids: biggest[1] } : undefined;
22
+ }
23
+ /** The kinds that are the app's people: declared so, else by their words. */
24
+ export function peopleKinds(store) {
25
+ const schema = store.schema;
26
+ const flagged = schema.definitions.filter((definition) => definition.people).map((definition) => definition.kind);
27
+ // Declared so, and those whose words say so (the rota's volunteers beside its users).
28
+ return [...new Set([...flagged, ...schema.definitions.filter((definition) => [definition.kind, definition.noun, pluralOf(schema, definition.kind)].some((word) => word !== undefined && PEOPLE.has(word.toLowerCase()))).map((definition) => definition.kind)])];
29
+ }
30
+ /** The giving the words say, and to whom: "assign … to Sam" → "assigned to", "Sam". */
31
+ export function givingOf(words) {
32
+ // A person named without "to": "Sam should take care of these", "make this Nora's job", "these are Ada's".
33
+ const owner = /^\s*([\p{L}][\p{L}'’-]*)\s+(?:should|can|will|could|is going to|needs to)\s+(?:take care of|handle|own|do|look after|take|deal with|pick up|be on)\b/iu.exec(words)?.[1] ??
34
+ /\bmake\s+(?:this|these|it|them|this one)\s+([\p{L}][\p{L}-]*)['’]s\b/iu.exec(words)?.[1] ??
35
+ /\b(?:this|these|it|they)\s+(?:is|are)\s+([\p{L}][\p{L}-]*)['’]s\b/iu.exec(words)?.[1] ??
36
+ /\b([\p{L}][\p{L}-]*)['’]s\s+(?:job|task|responsibility|shift|now)\b/iu.exec(words)?.[1] ??
37
+ // Who has it, said as a statement: "Sam's on this", "Sam has this one", "Sam is doing this", "Sam's got these".
38
+ /^\s*([\p{L}][\p{L}-]*)['’]s\s+(?:on|got|doing|handling|taking|covering)\s+(?:this|it|these|that|them)\b/iu.exec(words)?.[1] ??
39
+ /^\s*([\p{L}][\p{L}-]*)\s+(?:has|has got|is on|is doing|is handling|is taking|is covering|takes|does|owns)\s+(?:this|it|these|that|them)(?:\s+one)?\b/iu.exec(words)?.[1];
40
+ if (owner && !/^(it|this|that|these|those|they|we|you|i|he|she|everyone|someone|anyone|nobody|nothing|who|what|which|there|it's|that's|who's|what's)$/i.test(owner))
41
+ return { called: "assigned to", who: capital(owner), owned: true };
42
+ const who = /\bto\s+([\p{L}][\p{L}'’-]*)\s*[.!?]*\s*$/iu.exec(words)?.[1];
43
+ const verb = words
44
+ .toLowerCase()
45
+ .split(/[^a-z]+/)
46
+ .find((word) => word in GIVING);
47
+ if (!verb)
48
+ return undefined;
49
+ // The link is named by its role, whatever verb was typed: "give this to Nora" and "assign it to Nora" both want "assigned to".
50
+ return { called: "assigned to", ...(who ? { who: capital(who) } : {}) };
51
+ }
52
+ /** The fields that say a record is finished, read by a reply that narrows to the open ones. */
53
+ const DONE = ["done", "completed", "finished", "closed"];
54
+ /** The fields that say when a record is due, read for the late ones. */
55
+ const DUE = ["due", "dueDate", "dueOn", "deadline"];
56
+ /**
57
+ * WORDS THE READING DOES NOT ACCOUNT FOR: a restrictive clause ("that's
58
+ * already ticked off", "which are late", "the ones I've done", "except…")
59
+ * or a narrowing adjective ("the old ones"), read against a reading of
60
+ * everything held. A part (done, open, late) accounts for its clause; all
61
+ * of them accounts for none.
62
+ */
63
+ export function unaccounted(said, reading) {
64
+ if (reading.which !== "held" || reading.part)
65
+ return false;
66
+ return /\b(that'?s|that is|that are|that were|that have|that has|which|whose|already|except|but not|only|apart from|other than)\b/i.test(said) || /\bones? (that|which|i|we|you|i'?ve|we'?ve|i'?m)\b/i.test(said) || unreadNarrowing(said) || narrowingOf(said).open || narrowingOf(said).finished;
67
+ }
68
+ /** The best of a Choice and how sure, or nothing. */
69
+ function best(answer) {
70
+ if (answer?.type !== "choice")
71
+ return undefined;
72
+ const chance = answer.probabilities[answer.choice] ?? answer.confidence;
73
+ return { key: answer.choice, chance };
74
+ }
75
+ export async function decideOverTheGraph(fast, options) {
76
+ const { store, target, said } = options;
77
+ const schema = store.schema;
78
+ const words = `${said} ${options.follows?.said ?? ""}`.trim();
79
+ /* THE READINGS: the record itself, and the records it holds (or the list's own records). */
80
+ const self = target.on === "record" ? store.graph.getNode(target.id) : undefined;
81
+ const held = self ? heldBy(store, self.id) : undefined;
82
+ const listed = (options.members ?? []).filter((id) => store.graph.getNode(id) !== undefined);
83
+ const readings = [];
84
+ const where = options.where ? ` in ${options.where}` : self ? ` in ${labelOf(schema.tryDefinition(self.kind), self)}` : "";
85
+ const plural = (kind) => pluralOf(schema, kind).toLowerCase();
86
+ const noun = (kind) => (schema.tryDefinition(kind)?.noun ?? kind).toLowerCase();
87
+ if (self)
88
+ readings.push({ which: "itself", records: [self.id], kind: self.kind, words: `${labelOf(schema.tryDefinition(self.kind), self)} itself`, close: false });
89
+ const all = held ?? (listed.length > 0 ? { kind: store.graph.getNode(listed[0]).kind, ids: listed.filter((id) => store.graph.getNode(id).kind === store.graph.getNode(listed[0]).kind) } : undefined);
90
+ const counted = (ids, kind, part) => `the ${ids.length}${part ? ` ${part}` : ""} ${ids.length === 1 ? noun(kind) : plural(kind)}${where}`;
91
+ if (all && all.ids.length > 0)
92
+ readings.push({ which: "held", records: all.ids, kind: all.kind, words: counted(all.ids, all.kind), close: false });
93
+ /* A reply that only names the field keeps the reading it replies to: "call it owner" in a reply names the link the plan before it adds; said first, "call it X" renames the record. */
94
+ const renamed = options.follows ? /\bcall (?:it|that|the field)\s+["“']?([\p{L}][\p{L} ]*?)["”']?\s*[.!]*\s*$/iu.exec(said)?.[1] : undefined;
95
+ if (renamed && options.follows?.reading && readings.some((one) => one.which === options.follows.reading))
96
+ readings.splice(0, readings.length, ...readings.filter((one) => one.which === options.follows.reading));
97
+ if (readings.length === 0)
98
+ return { sure: false, usage: { inputTokens: 0, outputTokens: 0 } };
99
+ /*
100
+ * WHICH RECORDS, AS PARTS CODE CAN NAME. Beside the record itself and
101
+ * everything it holds, the parts of what it holds that code can say
102
+ * exactly — the done ones, the open ones, the late ones — are readings
103
+ * of their own, and Jev chooses among them, or "something else". No list
104
+ * of narrowing words decides it: they are a hint in the question.
105
+ */
106
+ const isDone = (id) => DONE.some((field) => store.graph.getNode(id)?.[field] === true);
107
+ const today = store.today?.() ?? new Date().toISOString().slice(0, 10);
108
+ const dueOf = (id) => DUE.map((field) => store.graph.getNode(id)?.[field]).find((value) => typeof value === "string");
109
+ const parts = [];
110
+ if (all && all.ids.length > 1) {
111
+ const done = all.ids.filter(isDone);
112
+ const open = all.ids.filter((id) => !isDone(id));
113
+ const late = open.filter((id) => (dueOf(id) ?? "9999") < today.slice(0, 10));
114
+ if (done.length > 0 && done.length < all.ids.length)
115
+ parts.push({ which: "held", part: "done", records: done, kind: all.kind, words: counted(done, all.kind, "done"), close: false });
116
+ if (open.length > 0 && open.length < all.ids.length)
117
+ parts.push({ which: "held", part: "open", records: open, kind: all.kind, words: counted(open, all.kind, "open"), close: false });
118
+ if (late.length > 0 && late.length < all.ids.length)
119
+ parts.push({ which: "held", part: "late", records: late, kind: all.kind, words: counted(late, all.kind, "late"), close: false });
120
+ }
121
+ const choices = renamed ? readings : [...readings, ...parts];
122
+ const keyOf = (one) => one.part ?? one.which;
123
+ /* THE QUESTIONS, ONE CALL: which records, which act on them (said by what it does), which record the words name, and — where none — what the app would need. */
124
+ const questions = {};
125
+ if (choices.length > 1)
126
+ questions["reading"] = { type: "choice", instructions: `Someone said “${said}”${options.follows ? `, replying to “${options.follows.said}”${options.follows.reading ? `, which was taken as ${options.follows.reading === "itself" ? "the record itself" : "the records it holds"}` : ""}` : ""}. Which records do they mean? "This", "it" or its name alone is the record itself; "these", "all", "them", "everything", "the lot" are never the record itself but every record it holds — unless more words say which of them: "the done ones", "that are finished", "already ticked off", "completed" mean the done ones; "outstanding", "remaining", "unfinished", "still to do", "except the done ones" mean the open ones; "late" or "overdue" the late ones. A word that says the change to make ("mark these done", "close these", "finish them") says what to do, not which records. If their words pick out some records in a way none of these says ("the old ones"), choose "something else".`, criteria: { ...Object.fromEntries(choices.map((one) => [keyOf(one), one.which === "itself" ? `${capital(one.words)} (the ${noun(one.kind)})` : capital(one.words)])), else: "Something else: some other part of them" } };
127
+ /* Asks or tells: whether the words want an answer in words or a change made — Jev's call on every utterance; the code's patterns only a hint where Jev is unsure. */
128
+ /* Inside the app or outside it: sending an email or a text, calling, paying, booking or posting somewhere is not a change to a record, and never a field to add. */
129
+ questions["where"] = { type: "choice", instructions: `Does “${said}” want something done to the records of this app (or an answer about them), or something done outside the app — an email or a text sent, a call made, a payment, a booking, a post somewhere?`, criteria: { inside: "Inside the app: its records, or an answer about them", outside: "Outside the app: send, call, pay, book or post somewhere else" } };
130
+ questions["mood"] = { type: "choice", instructions: `Does “${said}” ask something, wanting an answer in words, or tell me to do something, wanting a change made? A question can come without a question mark ("has this been done yet"), an instruction can be polite ("could you close these"), and saying who has something ("Sam's on this", "Nora has this one") tells me to give it to them.`, criteria: { asks: "Asks something: wants an answer in words", tells: "Tells me to do something: wants a change made" } };
131
+ const actsOn = (kind) => store.allMutations().filter((mutation) => mutation.subject && (mutation.subject.kinds === "*" || mutation.subject.kinds.includes(kind)));
132
+ const offered = readings.flatMap((reading) => actsOn(reading.kind).slice(0, 24).map((mutation) => ({ key: `${reading.which}:${mutation.name}`, reading, mutation })));
133
+ questions["act"] = {
134
+ type: "choice",
135
+ instructions: `Which of these acts does “${words}” ask to be done? Judge each by what it does, not only its title: people say "close", "complete", "check off", "tick" or "finish" for an act that marks something done, "delete" for one that removes, "push" or "move" for one that changes a date or a place. A question, or "undo that", is none of them. "none" only where no act here does it.`,
136
+ criteria: { ...Object.fromEntries(offered.map((one) => [one.key, `${one.mutation.title ?? one.mutation.name}: ${sentenceOf(one.mutation.description)}${effectOf(one.mutation, schema, one.reading.kind)} — on ${one.reading.which === "itself" ? `the ${noun(one.reading.kind)} itself` : `each of ${one.reading.words}`}`])), none: "None of these acts does it" },
137
+ };
138
+ /* The records the words may name: the app's people, and records of the kinds the acts here take — those whose names the words share, where there are many. */
139
+ const kindsOfPeople = peopleKinds(store);
140
+ const refKinds = new Set([...kindsOfPeople, ...offered.flatMap((one) => nodeRefArgs(one.mutation.input).filter((ref) => ref.name !== one.mutation.subject.arg).flatMap((ref) => ref.kinds))]);
141
+ const ofRefKinds = store.graph.allNodes().filter((node) => refKinds.has(node.kind) || refKinds.has("*"));
142
+ const stems = new Set(words.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((word) => word.length >= 3).map((word) => word.slice(0, 4)));
143
+ const labeled = (node) => labelOf(schema.tryDefinition(node.kind), node);
144
+ const nameable = (ofRefKinds.length <= 25 ? ofRefKinds : ofRefKinds.filter((node) => labeled(node).toLowerCase().split(/[^\p{L}\p{N}]+/u).some((word) => word.length >= 3 && stems.has(word.slice(0, 4))))).filter((node) => node.id !== self?.id && !readings.some((one) => one.records.includes(node.id))).slice(0, 25);
145
+ /*
146
+ * PEOPLE SAID AS PRONOUNS. "Me", "my", "mine", "myself" are the person at
147
+ * the seat: their own record, or the record of a kind an act takes that
148
+ * bears their name. "Her", "him", "them", "that person" are someone the
149
+ * context gives: a person the record links, the one named in the turn
150
+ * before. One is taken; several, Jev chooses — and the card says whom.
151
+ */
152
+ const meAt = MINE.test(said) ? principalRecord(store, options.principal, refKinds) : undefined;
153
+ const meName = MINE.test(said) && options.principal ? nameOfRecord(store, options.principal.id) : undefined;
154
+ const theirsSaid = THEIRS.exec(said);
155
+ const pronoun = (theirsSaid?.[1] ?? theirsSaid?.[2])?.toLowerCase();
156
+ const fromContext = pronoun ? contextPeople(store, self?.id, options.follows?.said, kindsOfPeople) : [];
157
+ if (pronoun && fromContext.length > 1)
158
+ questions["pronoun"] = { type: "choice", instructions: `In “${said}”${options.follows ? `, said after “${options.follows.said}”` : ""}, whom does “${pronoun}” mean?`, criteria: { ...Object.fromEntries(fromContext.map((node) => [`r:${node.id}`, labeled(node)])), else: "Someone else" } };
159
+ if (nameable.length > 0)
160
+ questions["named"] = { type: "choice", instructions: `Which of these does “${words}” name, as the one to give it to, move it to, link it with or put it on?`, criteria: { ...Object.fromEntries(nameable.map((node) => [`r:${node.id}`, `${labeled(node)} (${withArticle(noun(node.kind))})`])), new: "Someone or something not listed here", none: "None is named" } };
161
+ questions["need"] = { type: "choice", instructions: `If no act here can do “${words}”, what would each record need?`, criteria: { person: "A link to the person it is given or assigned to", other: "Something else: a field, a date, a number, a note", none: "Nothing: an act here can do it" } };
162
+ /* What this app's people said before and what worked (Roadmap f-menu-learns): examples, by name, for the same typed questions. */
163
+ const decided = await fast.decide({ said, ...(options.follows ? { replyingTo: options.follows.said } : {}), readings: choices.map((one) => one.words), ...(options.examples && options.examples.length > 0 ? { workedBefore: options.examples } : {}) }, questions);
164
+ const mood = best(decided.answers["mood"]);
165
+ // Who has it, said as a statement ("Sam's on this"), gives it to them: a telling, whatever the mood's chance.
166
+ const ownerSaid = givingOf(said)?.owned === true && !/\?\s*$/.test(said);
167
+ const question = ownerSaid ? false : mood && mood.chance >= 0.6 ? mood.key === "asks" : asking(said);
168
+ /* An outside action: said plainly that it is not done from here, with the record's own link where it has one — never a plan to add a field. */
169
+ const whereTo = best(decided.answers["where"]);
170
+ if (!question && outsideVerb(said) && whereTo?.key === "outside" && whereTo.chance >= 0.6)
171
+ return { sure: true, asks: false, outside: outsideWords(store, said, self?.id), usage: decided.usage };
172
+ const reading0 = best(decided.answers["reading"]);
173
+ const reading = choices.length > 1 ? choices.find((one) => keyOf(one) === reading0?.key) : choices[0];
174
+ if (!reading) {
175
+ // "Something else" for an act that removes or sets aside: which records, asked back — never guessed.
176
+ const top = best(decided.answers["act"]);
177
+ const leaning = top && top.key !== "none" ? offered.find((one) => one.key === top.key) : undefined;
178
+ if (!question && leaning && removing(leaning.mutation) && all && all.ids.length > 1) {
179
+ const verb = (leaning.mutation.title ?? leaning.mutation.name).trim().split(/\s+/)[0].toLowerCase();
180
+ return { sure: true, asks: false, clarify: `Which of the ${all.ids.length} ${plural(all.kind)}${where} should I ${verb}? Say which, or “all”.`, usage: decided.usage };
181
+ }
182
+ return { sure: false, asks: question, usage: decided.usage };
183
+ }
184
+ const chosen = { ...reading, close: choices.length > 1 && (reading0?.chance ?? 1) < READING_SURE, chance: choices.length > 1 ? (reading0?.chance ?? 0) : 1 };
185
+ const act = best(decided.answers["act"]);
186
+ const named = best(decided.answers["named"]);
187
+ const chosenPronoun = best(decided.answers["pronoun"]);
188
+ const theirs = pronoun ? (fromContext.length === 1 ? fromContext[0] : chosenPronoun?.key.startsWith("r:") ? store.graph.getNode(chosenPronoun.key.slice(2)) : undefined) : undefined;
189
+ const taken = pronoun && theirs ? { said: pronoun, as: labeled(theirs) } : undefined;
190
+ const namedNode = meAt ?? theirs ?? (named?.key.startsWith("r:") && named.chance >= GRAPH_SURE ? store.graph.getNode(named.key.slice(2)) : undefined);
191
+ // The person the words give it to: said here, else in the turn before; a pronoun, as the context took it.
192
+ const givenHere = givingOf(said) ?? givingOf(words);
193
+ const whoSaid = givenHere?.who && (MINE.test(givenHere.who) ? meAt ? labeled(meAt) : meName : THEIRS_WORD.test(givenHere.who) ? (theirs ? labeled(theirs) : undefined) : givenHere.who);
194
+ const given = givenHere ? { called: givenHere.called, ...(whoSaid ? { who: whoSaid } : {}), ...(givenHere.owned ? { owned: true } : {}) } : undefined;
195
+ const giving = given && renamed ? { ...given, called: renamed.toLowerCase() } : given;
196
+ // Sure of the reading: likelier than not, or well ahead of the next (a typo spreads Jev's chance: "mrk these done").
197
+ const second = decided.answers["reading"]?.type === "choice" ? Object.entries(decided.answers["reading"].probabilities).filter(([key]) => key !== reading0?.key).reduce((most, [, chance]) => Math.max(most, chance), 0) : 0;
198
+ const sureOfReading = choices.length === 1 || (reading0?.chance ?? 0) >= 0.5 || ((reading0?.chance ?? 0) >= 0.35 && (reading0?.chance ?? 0) >= 1.5 * second);
199
+ if (!sureOfReading)
200
+ return { sure: false, asks: question, reading: chosen, usage: decided.usage };
201
+ /* AN ACT CAN DO IT: the one Jev picked, on the reading's records, its values filled from the graph — else the light model fills them. */
202
+ const takesRefTo = (mutation, kinds) => nodeRefArgs(mutation.input).some((ref) => ref.name !== mutation.subject.arg && (ref.kinds.includes("*") || ref.kinds.some((kind) => kinds.includes(kind))));
203
+ const giveTo = [...kindsOfPeople, ...(namedNode ? [namedNode.kind] : [])];
204
+ /* A question, or "undo that", is not an act to propose: the light model answers it in words. */
205
+ if (question || UNDOING.test(said))
206
+ return { sure: false, asks: question, reading: chosen, usage: decided.usage };
207
+ const ranks = actRanks(decided.answers["act"]);
208
+ const onReading = (name) => offered.find((one) => one.mutation.name === name && one.reading.which === chosen.which);
209
+ const removes = (one) => Boolean(one && (one.mutation.destructive || one.mutation.derived?.act === "remove"));
210
+ let mutationName = act && act.key !== "none" ? act.key.slice(act.key.indexOf(":") + 1) : undefined;
211
+ let sureOfAct = act !== undefined && act.key !== "none" && act.chance >= GRAPH_SURE;
212
+ // Two acts that do the same thing ("Drop it", "Remove the task") split Jev's chance between them: together they are sure.
213
+ if (!sureOfAct && ranks.length > 1 && ranks[0].chance + ranks[1].chance >= 0.8 && removes(onReading(ranks[0].name)) && removes(onReading(ranks[1].name)))
214
+ sureOfAct = true;
215
+ // The record the words name decides between acts: "move this to Someday" names a list, so the act that takes a list.
216
+ if (mutationName && namedNode && onReading(mutationName) && !takesRefTo(onReading(mutationName).mutation, [namedNode.kind])) {
217
+ // An act whose values code cannot fill ("Move the date" wants a date) gives way to one that takes the record named, when it is named surely.
218
+ const leaning = onReading(mutationName).mutation;
219
+ const refNames = new Set(nodeRefArgs(leaning.input).map((ref) => ref.name));
220
+ const wantsAValue = Object.entries(leaning.input?.shape ?? {}).some(([arg, field]) => !refNames.has(arg) && !field.safeParse(undefined).success && !field.safeParse(calledTo(said)).success);
221
+ const floor = named && named.chance >= 0.9 && wantsAValue ? 0 : 0.05;
222
+ const taking = ranks.filter((one) => one.chance >= floor).map((one) => onReading(one.name)).find((one) => one && one.mutation.derived?.act !== "merge" && takesRefTo(one.mutation, [namedNode.kind]));
223
+ if (taking) {
224
+ mutationName = taking.mutation.name;
225
+ sureOfAct = true;
226
+ }
227
+ }
228
+ // Given to a person code resolved (a pronoun, "me", "X should…"), and one act here takes them: that act, whatever Jev weighed.
229
+ if (!sureOfAct && namedNode && giving?.who && (taken || meAt || giving.owned)) {
230
+ const takers = offered.filter((one) => one.reading.which === chosen.which && one.mutation.derived?.act !== "merge" && nodeRefArgs(one.mutation.input).some((ref) => ref.name !== one.mutation.subject.arg && sameAs(store, namedNode, ref.kinds) !== undefined && kindsOfPeople.some((kind) => ref.kinds.includes(kind))));
231
+ if (takers.length === 1) {
232
+ mutationName = takers[0].mutation.name;
233
+ sureOfAct = true;
234
+ }
235
+ }
236
+ // A record the words name, and one act here that takes it, likely enough: that act ("give this to her" — Ada — is "Cover it").
237
+ if (!sureOfAct && namedNode) {
238
+ const taking = ranks.filter((one) => one.chance >= 0.3).map((one) => onReading(one.name)).find((one) => one && one.mutation.derived?.act !== "merge" && nodeRefArgs(one.mutation.input).some((ref) => ref.name !== one.mutation.subject.arg && sameAs(store, namedNode, ref.kinds) !== undefined));
239
+ if (taking) {
240
+ mutationName = taking.mutation.name;
241
+ sureOfAct = true;
242
+ }
243
+ }
244
+ /* A RENAME SAID AS A STATEMENT ("the name should be X", "call it X", "X is a better name"): the act that writes the record's name, on the record itself, its value the words' — read by code. */
245
+ const newName = renamed === undefined ? renameOf(said) : undefined;
246
+ const itself = readings.find((one) => one.which === "itself");
247
+ if (newName && itself) {
248
+ // The act that names the record: it takes one value besides the record, and that value is its name (it writes it, or the argument is called so).
249
+ const NAMES = ["label", "name", "title"];
250
+ const naming = offered.find((one) => {
251
+ const rest = (argumentsTaken(one.mutation) ?? []).filter((arg) => arg !== one.mutation.subject.arg);
252
+ return one.reading.which === "itself" && rest.length === 1 && (NAMES.includes(rest[0]) || (one.mutation.writes ?? []).some((field) => NAMES.includes(field)));
253
+ });
254
+ const arg = naming ? (argumentsTaken(naming.mutation) ?? []).find((one) => one !== naming.mutation.subject.arg) : undefined;
255
+ const field = arg ? (naming.mutation.input?.shape ?? {})[arg] : undefined;
256
+ if (naming && arg && field?.safeParse(newName).success) {
257
+ return { sure: true, reading: { ...itself, close: false }, each: { act: naming.mutation.name, args: { [arg]: newName } }, usage: decided.usage };
258
+ }
259
+ }
260
+ // Jev's act on the other reading ("Archive the list" where the words meant the tasks): the same act on the reading chosen.
261
+ if (mutationName && !onReading(mutationName)) {
262
+ const meant = offered.find((one) => one.mutation.name === mutationName);
263
+ const same = (other) => {
264
+ const a = meant?.mutation?.derived?.act;
265
+ const b = other.mutation.derived?.act;
266
+ return a !== undefined ? a === b : (other.mutation.title ?? other.mutation.name).split(/\s+/)[0].toLowerCase() === (meant?.mutation.title ?? mutationName ?? "").split(/\s+/)[0].toLowerCase();
267
+ };
268
+ const twin = offered.find((one) => one.reading.which === chosen.which && same(one));
269
+ if (twin)
270
+ mutationName = twin.mutation.name;
271
+ }
272
+ const picked = mutationName && sureOfAct ? onReading(mutationName) : undefined;
273
+ // Words that give a record to someone are done only by an act that takes them.
274
+ if (picked && !(giving?.who && !takesRefTo(picked.mutation, giveTo))) {
275
+ const rest = (argumentsTaken(picked.mutation) ?? []).filter((arg) => arg !== picked.mutation.subject.arg);
276
+ const refs = nodeRefArgs(picked.mutation.input);
277
+ const shape = (picked.mutation.input?.shape ?? {});
278
+ const args = {};
279
+ let complete = true;
280
+ for (const arg of rest) {
281
+ const ref = refs.find((one) => one.name === arg);
282
+ const optional = ref ? ref.optional : (shape[arg]?.safeParse(undefined).success ?? true);
283
+ const meant = ref && namedNode ? sameAs(store, namedNode, ref.kinds) : undefined;
284
+ if (ref && meant)
285
+ args[arg] = meant.id;
286
+ else if (!ref && !optional && rest.filter((one) => !refs.some((r) => r.name === one)).length === 1 && calledTo(said) !== undefined && shape[arg]?.safeParse(calledTo(said)).success)
287
+ args[arg] = calledTo(said);
288
+ else if (!optional)
289
+ complete = false;
290
+ }
291
+ // A change that changes nothing (an edit with no value) is not an answer.
292
+ if (picked.mutation.derived?.act === "edit" && Object.keys(args).length === 0)
293
+ complete = false;
294
+ if (!complete)
295
+ return { sure: false, reading: chosen, ...(taken ? { taken } : {}), act: picked.mutation.name, usage: decided.usage };
296
+ /*
297
+ * A DESTRUCTIVE ACT OVER SEVERAL NEEDS A CLEAR READING. "Drop the ones
298
+ * I've done" once proposed dropping all 6 tasks: an act that removes or
299
+ * sets aside is offered over more than one record only where the words
300
+ * said which (all of them, or the done or open ones) or Jev was sure of
301
+ * the reading; else the card asks which.
302
+ */
303
+ /* Over several: Jev sure of the reading (0.9), and no restrictive words left that the reading does not account for ("everything that's already ticked off" read as everything). */
304
+ const readingSure = choices.length === 1 || (reading0?.chance ?? 0) >= barFor(picked.mutation, said);
305
+ if (removing(picked.mutation) && chosen.records.length > 1 && (!readingSure || unaccounted(said, chosen))) {
306
+ return { sure: true, reading: chosen, clarify: whichOf(store, picked.mutation.title ?? picked.mutation.name, chosen), usage: decided.usage };
307
+ }
308
+ return { sure: true, reading: chosen, ...(taken ? { taken } : {}), each: { act: picked.mutation.name, args }, usage: decided.usage };
309
+ }
310
+ /* NONE CAN: code, not the model's wording, says no act here gives these records to someone — and only then what the app lacks: a link to the person the words name. */
311
+ const need = best(decided.answers["need"]);
312
+ const anActGives = offered.some((one) => one.reading.which === chosen.which && takesRefTo(one.mutation, giveTo));
313
+ if (giving?.who && !anActGives && ((need?.key === "person" && need.chance >= GRAPH_SURE) || meAt !== undefined || meName !== undefined || taken !== undefined || giving.owned === true)) {
314
+ const who = giving.who ?? (namedNode && kindsOfPeople.includes(namedNode.kind) ? labeled(namedNode) : undefined);
315
+ if (!who)
316
+ return { sure: false, reading: chosen, usage: decided.usage };
317
+ const lacks = renamed ? `${capital(plural(chosen.kind))} have no ${giving.called}.` : `${capital(plural(chosen.kind))} have no one ${giving.called} them.`;
318
+ return { sure: true, reading: chosen, ...(taken ? { taken } : {}), missing: { said: lacks, need: { link: { on: chosen.kind, called: giving.called, to: "person" } }, who }, text: lacks, usage: decided.usage };
319
+ }
320
+ return { sure: false, reading: chosen, ...(taken ? { taken } : {}), ...(mutationName && act && act.chance >= 0.3 ? { act: mutationName } : {}), usage: decided.usage };
321
+ }
322
+ /** "Me", "my", "mine", "myself": the person at the seat. */
323
+ const MINE = /\b(me|my|mine|myself)\b/i;
324
+ /** Someone the context gives, where the words name a person by a pronoun. */
325
+ const THEIRS = /\b(?:to|off|from|for|with)\s+(her|him|them|that person|whoever)\b|\b(?:take|put|move|swap|drop)\s+(her|him)\b/i;
326
+ const THEIRS_WORD = /^(her|him|them|they|that person|whoever)$/i;
327
+ /** The seat's own record: theirs by id, else one of a kind an act takes that bears their name. */
328
+ function principalRecord(store, principal, kinds) {
329
+ if (!principal)
330
+ return undefined;
331
+ const own = store.graph.getNode(principal.id);
332
+ const name = own ? labelOf(store.schema.tryDefinition(own.kind), own).toLowerCase() : undefined;
333
+ const bearing = name ? store.graph.allNodes().find((node) => node.id !== principal.id && kinds.has(node.kind) && labelOf(store.schema.tryDefinition(node.kind), node).toLowerCase() === name) : undefined;
334
+ // A record of a kind an act takes comes first ("take this off me": the volunteer, not the user).
335
+ return bearing ?? (own && kinds.has(own.kind) ? own : own);
336
+ }
337
+ /** What the seat is called, from its record. */
338
+ function nameOfRecord(store, id) {
339
+ const node = store.graph.getNode(id);
340
+ return node ? labelOf(store.schema.tryDefinition(node.kind), node) : undefined;
341
+ }
342
+ /** The people a pronoun may mean: those the record links, then those the turn before names. */
343
+ function contextPeople(store, id, before, kinds) {
344
+ const schema = store.schema;
345
+ const linked = id ? [...store.graph.in(id), ...store.graph.out(id)].filter((node) => kinds.includes(node.kind)) : [];
346
+ const words = (before ?? "").toLowerCase();
347
+ const named = words ? store.graph.allNodes().filter((node) => kinds.includes(node.kind) && labelOf(schema.tryDefinition(node.kind), node).toLowerCase().split(/\s+/).some((word) => word.length >= 3 && new RegExp(`\\b${word.replace(/[^\p{L}\p{N}]/gu, "")}\\b`, "u").test(words))) : [];
348
+ // The turn before names whom it means; the record's own links are the rest.
349
+ const all = [...named, ...linked];
350
+ // One person once: the user Ada and the volunteer Ada are one Ada.
351
+ const nameOf = (node) => labelOf(schema.tryDefinition(node.kind), node).toLowerCase();
352
+ return all.filter((node, index) => all.findIndex((other) => nameOf(other) === nameOf(node)) === index).slice(0, 8);
353
+ }
354
+ /** The record the words mean, as a kind an act takes: itself, or the one of that kind bearing its name (the user Ada as the volunteer Ada). */
355
+ function sameAs(store, node, kinds) {
356
+ if (kinds.includes("*") || kinds.includes(node.kind))
357
+ return node;
358
+ const schema = store.schema;
359
+ const name = labelOf(schema.tryDefinition(node.kind), store.graph.getNode(node.id)).toLowerCase();
360
+ return store.graph.allNodes().find((other) => kinds.includes(other.kind) && labelOf(schema.tryDefinition(other.kind), other).toLowerCase() === name);
361
+ }
362
+ /**
363
+ * TWO ASKS IN ONE SENTENCE: "archive the done ones, then close the rest" is
364
+ * two parts, each an instruction of its own. Split at "and", "then", ", then"
365
+ * or "; " only where each side begins with a verb-like word and says more
366
+ * than a word — so "assign these to Sam and Nora" and "rename it to Pack and
367
+ * Go" stay one.
368
+ */
369
+ export function askedParts(said) {
370
+ const parts = said
371
+ .split(/\s*(?:,\s*and then|,\s*then|\band then\b|;|\bthen\b|,?\s+and\s+)\s*/i)
372
+ .map((part) => part.trim())
373
+ .filter(Boolean);
374
+ if (parts.length < 2 || parts.length > 3)
375
+ return [said];
376
+ const NOT_A_VERB = /^(the|a|an|my|our|your|this|these|that|those|all|every|each|some|it|them|they|he|she|i|we|you|to|for|with|on|in|at|by|of|from|tomorrow|today|tonight|monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i;
377
+ const instruction = (part) => {
378
+ const words = part.split(/\s+/);
379
+ return words.length >= 2 && /^[a-z]/.test(words[0]) && !NOT_A_VERB.test(words[0]);
380
+ };
381
+ return parts.every(instruction) ? parts : [said];
382
+ }
383
+ /**
384
+ * WORDS THAT NARROW TO DONE OR OPEN RECORDS, however they are said:
385
+ * "finished", "completed", "the done stuff", "ones I've done", "outstanding",
386
+ * "remaining", "unfinished", "still to do". A bare "open" ("open this") is a
387
+ * verb unless a reply narrows with it.
388
+ */
389
+ export function narrowingOf(said, replying = false) {
390
+ const words = said.toLowerCase();
391
+ const finished = /\b(done|finished|completed|complete|closed|ticked|checked)( off)? (ones?|tasks?|items?|stuff|things|bits)\b/.test(words) ||
392
+ /\b(ones?|tasks?|items?|things|stuff) (i'?ve|we'?ve|i have|we have|that are|that'?s|already) (done|finished|completed|closed|ticked off)\b/.test(words) ||
393
+ /\balready (done|finished|completed)\b/.test(words) ||
394
+ /\bthe (finished|completed)\b/.test(words);
395
+ const open = /\b(outstanding|remaining|unfinished|undone|incomplete|pending)\b/.test(words) ||
396
+ /\b(still to do|left to do|not done|not finished|not yet done)\b/.test(words) ||
397
+ /\b(open) (ones?|tasks?|items?|stuff|things)\b/.test(words) ||
398
+ (replying && /\bopen\b/.test(words));
399
+ return finished && open ? { open: false, finished: false } : { open, finished };
400
+ }
401
+ /** Whether the words say which records: all of them, or the done or open ones. */
402
+ export function explicitReading(said) {
403
+ const { open, finished } = narrowingOf(said);
404
+ if (open || finished)
405
+ return true;
406
+ // A word that narrows in a way code does not read ("the old ones", "the big tasks") leaves the reading unclear, however sure Jev is.
407
+ if (unreadNarrowing(said))
408
+ return false;
409
+ return /\b(all|every|each|everything|the lot|the whole (list|lot)|every one|both|these|those)\b/i.test(said);
410
+ }
411
+ /** "The old ones", "the urgent tasks": a word narrowing the records that is neither done nor open — code cannot say which those are. */
412
+ export function unreadNarrowing(said) {
413
+ const found = /\bthe ([a-z]+) (ones?|tasks?|items?|stuff|things|shifts?|songs?)\b/i.exec(said)?.[1]?.toLowerCase();
414
+ return found !== undefined && !["other", "rest", "whole", "same"].includes(found) && !narrowingOf(`the ${found} ones`).open && !narrowingOf(`the ${found} ones`).finished;
415
+ }
416
+ /**
417
+ * HOW SURE JEV MUST BE of the records before an act that takes some away
418
+ * runs over several. Setting aside (archive, brought back by unarchive)
419
+ * runs at 0.75 where the words name every record ("these", "all",
420
+ * "everything"); removing — gone, not set aside — at 0.9, always.
421
+ */
422
+ export function barFor(mutation, said) {
423
+ const settingAside = mutation.derived?.act === "archive" && mutation.destructive !== true;
424
+ return settingAside && /\b(these|those|all|everything|every one|each|them|the lot|the whole (list|lot))\b/i.test(said) ? 0.75 : 0.9;
425
+ }
426
+ /** An act that removes or sets aside: one that must be meant for exactly the records it takes. */
427
+ export function removing(mutation) {
428
+ return mutation.destructive === true || mutation.derived?.act === "remove" || mutation.derived?.act === "archive";
429
+ }
430
+ /** The question back: "Should I drop the 1 done task, or all 6 tasks in This week?" */
431
+ function whichOf(store, title, reading) {
432
+ const schema = store.schema;
433
+ const verb = title.trim().split(/\s+/)[0].toLowerCase();
434
+ const isDone = (id) => DONE.some((field) => store.graph.getNode(id)?.[field] === true);
435
+ const done = reading.records.filter(isDone);
436
+ const noun = (schema.tryDefinition(reading.kind)?.noun ?? reading.kind).toLowerCase();
437
+ const many = pluralOf(schema, reading.kind).toLowerCase();
438
+ const where = / (in .+)$/.exec(reading.words)?.[1];
439
+ const all = `all ${reading.records.length} ${many}${where ? ` ${where}` : ""}`;
440
+ if (done.length > 0 && done.length < reading.records.length)
441
+ return `Should I ${verb} the ${done.length} done ${done.length === 1 ? noun : many}, or ${all}?`;
442
+ return `Should I ${verb} ${all}? Say “all” to go ahead, or say which.`;
443
+ }
444
+ /** The words begin with an act done outside the app ("email the landlord", "text Bo", "call the van company") — not "call it X", a rename. */
445
+ export function outsideVerb(said) {
446
+ const found = /^\s*(?:please\s+|pls\s+|could you\s+|can you\s+|would you\s+|can we\s+|let'?s\s+)?(e-?mail|mail|text|sms|message|whatsapp|call|phone|ring|dial|pay|venmo|book|reserve|post|tweet|share)\b(.*)$/i.exec(said);
447
+ // "Call it Boxes", "call this “Packing”": a name given, not a call made.
448
+ return found !== null && !/^\s+(?:it|this|that|this one)\s+(?:[A-Z“"']|as\b|to\b)/.test(found[2] ?? "");
449
+ }
450
+ /** What a request outside the app would be, in the words it is refused with. */
451
+ const OUTSIDE = [
452
+ [/\b(e-?mail|mail)\b/i, "send email"],
453
+ [/\b(text|sms|message|whatsapp|dm)\b/i, "send messages"],
454
+ [/\b(call|phone|ring|dial)\b/i, "make calls"],
455
+ [/\b(pay|venmo|transfer|invoice)\b/i, "make payments"],
456
+ [/\b(book|reserve)\b/i, "book things"],
457
+ [/\b(post|tweet|share)\b/i, "post outside this app"],
458
+ ];
459
+ /** "I can't send email from here." — and, where the record holds an email or a link, that it is there to open. */
460
+ export function outsideWords(store, said, id) {
461
+ const what = OUTSIDE.find(([pattern]) => pattern.test(said))?.[1] ?? "do things outside this app";
462
+ const node = id ? store.graph.getNode(id) : undefined;
463
+ const link = node ? Object.values(node).find((value) => typeof value === "string" && (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || /^https?:\/\//.test(value))) : undefined;
464
+ return link ? `I can't ${what} from here, but its ${link.includes("@") && !link.startsWith("http") ? "email" : "link"} is ${link} — open it to do that.` : `I can't ${what} from here: this app keeps your records, and doing that happens outside it.`;
465
+ }
466
+ /** Words that ask rather than tell: a question to answer, not an act to propose. */
467
+ export function asking(said) {
468
+ // Said politely or indirectly, it is still an instruction: "could you close these", "please…", "I'd like…", "X should…", "can we…".
469
+ if (politely(said))
470
+ return false;
471
+ // "Do" asks only with a subject after it ("do we have…"); "do what is left" tells.
472
+ return /\?\s*$/.test(said) || /^\s*(who|whom|whose|what|whats|what's|when|where|which|why|how|is|are|was|were|can|could|should|any|anything|tell me|show me|list)\b/i.test(said) || /^\s*(do|does|did)\s+(you|we|i|they|it|he|she|anyone|anybody|any)\b/i.test(said);
473
+ }
474
+ /** An instruction said politely or indirectly: a request, not a question to answer in words. */
475
+ export function politely(said) {
476
+ const words = said.trim().toLowerCase();
477
+ if (/^(please|pls|kindly)\b/.test(words))
478
+ return true;
479
+ if (/^(could|can|would|will) (you|we|u)\s+(please\s+)?(?!tell|say|explain|show me what|see)\w+/.test(words) && !/^(could|can|would|will) (you|we) (be|have)\b/.test(words))
480
+ return true;
481
+ if (/^(i'?d like|i would like|i want|i need|let'?s|we should|we need to)\b/.test(words))
482
+ return true;
483
+ // "These should be marked done", "Sam should take care of these": what ought to be, said of the records or of a person.
484
+ if (/^[\p{L}'’]+(\s[\p{L}'’]+)?\s+(should|needs to|need to|has to|have to|ought to)\s+(be\s+)?\w+/u.test(words) && !/^(what|who|which|when|where|why|how|is|are|do|does)\b/.test(words))
485
+ return true;
486
+ return false;
487
+ }
488
+ /** A rename said as a statement: "name should be X", "call it X", "X is a better name", "rename it to X" → "X". */
489
+ export function renameOf(said) {
490
+ const text = said.trim().replace(/[.!]+$/, "");
491
+ const forms = [
492
+ /^(?:the\s+|its\s+|this\s+|list\s+|task\s+)*name\s+should\s+be\s+["“']?(.+?)["”']?$/i,
493
+ /^(?:please\s+)?call\s+(?:this one|this list|this task|this shift|this song|it|this)\s+["“']?(.+?)["”']?$/i,
494
+ /^["“']?(.+?)["”']?\s+is\s+a\s+better\s+name$/i,
495
+ /^(?:please\s+)?(?:re)?name\s+(?:this one|this list|this task|this shift|this song|it|this)\s+(?:to\s+|as\s+)?["“']?(.+?)["”']?$/i,
496
+ /^(?:let'?s\s+)?call\s+(?:it|this)\s+["“']?(.+?)["”']?$/i,
497
+ ];
498
+ for (const form of forms) {
499
+ const found = form.exec(text)?.[1]?.trim();
500
+ if (found)
501
+ return found;
502
+ }
503
+ return undefined;
504
+ }
505
+ /** "Undo that": the app's own undo takes back the last change; no act here does. */
506
+ export const UNDOING = /^\s*(undo|take (that|it) back|revert|go back)\b/i;
507
+ /** The one value the words give "to" or "as": "rename this to Packing" → "Packing". */
508
+ function calledTo(said) {
509
+ const value = /\b(?:to|as)\s+["“']?(.+?)["”']?\s*[.!]?\s*$/i.exec(said)?.[1]?.trim();
510
+ return value && value.length > 0 ? value : undefined;
511
+ }
512
+ /** Every act Jev weighed, likeliest first, with how likely. */
513
+ function actRanks(answer) {
514
+ if (answer?.type !== "choice")
515
+ return [];
516
+ return Object.entries(answer.probabilities)
517
+ .filter(([key]) => key !== "none")
518
+ .sort((a, b) => b[1] - a[1])
519
+ .map(([key, chance]) => ({ name: key.slice(key.indexOf(":") + 1), chance }));
520
+ }
521
+ /** A description as the end of a sentence: its own words, a space after. */
522
+ function sentenceOf(description) {
523
+ const said = description?.trim();
524
+ return said ? `${said}${/[.!?]$/.test(said) ? "" : "."} ` : "";
525
+ }
526
+ /** What an act does, said from what it declares: the fields it writes, the links it makes and breaks, what it makes or removes. */
527
+ export function effectOf(mutation, schema, kind) {
528
+ const parts = [];
529
+ const args = (argumentsTaken(mutation) ?? []).filter((arg) => arg !== mutation.subject?.arg);
530
+ const refs = nodeRefArgs(mutation.input).filter((ref) => ref.name !== mutation.subject?.arg);
531
+ const shape = (schema.tryDefinition(kind)?.fields?.shape ?? {});
532
+ const typeOf = (field) => shape[field]?._zod?.def?.type === "optional" ? shape[field]?._zod?.def?.innerType?._zod?.def?.type : shape[field]?._zod?.def?.type;
533
+ const derived = mutation.derived?.act;
534
+ if (derived === "remove")
535
+ parts.push("removes it");
536
+ else if (derived === "archive")
537
+ parts.push("sets it aside in the archive");
538
+ else if (derived === "unarchive")
539
+ parts.push("brings it back from the archive");
540
+ else if (derived === "merge")
541
+ parts.push("merges it into another");
542
+ else if (derived === "edit")
543
+ parts.push("changes any of its fields to values given");
544
+ for (const field of mutation.writes ?? []) {
545
+ if (mutation.sets && field in mutation.sets)
546
+ parts.push(`sets ${field} to ${String(mutation.sets[field])}`);
547
+ else if (args.includes(field))
548
+ parts.push(`sets ${field} to a value given`);
549
+ else if (typeOf(field) === "boolean")
550
+ parts.push(`sets ${field} yes or no`);
551
+ else
552
+ parts.push(`changes ${field}`);
553
+ }
554
+ for (const arg of args)
555
+ if (!(mutation.writes ?? []).includes(arg) && !refs.some((ref) => ref.name === arg) && derived !== "edit")
556
+ parts.push(`takes ${arg}`);
557
+ const to = [...new Set(refs.flatMap((ref) => ref.kinds))].filter((one) => one !== "*").join(" or ");
558
+ if ((mutation.connects?.length ?? 0) > 0 && (mutation.severs?.length ?? 0) > 0)
559
+ parts.push(`moves it to another ${to || "record"}`);
560
+ else if ((mutation.connects?.length ?? 0) > 0)
561
+ parts.push(`links it to ${withArticle(to || "record")}`);
562
+ else if ((mutation.severs?.length ?? 0) > 0)
563
+ parts.push(`unlinks it from ${withArticle(to || "record")}`);
564
+ if (mutation.destructive && derived !== "remove")
565
+ parts.push("removes it for good");
566
+ if ((mutation.creates?.length ?? 0) > 0)
567
+ parts.push(`adds a new ${mutation.creates.join(" or ")}`);
568
+ return parts.length > 0 ? `(It ${parts.join(", ")}.)` : "";
569
+ }
570
+ //# sourceMappingURL=graph-plan.js.map