@yaks/memory 0.0.0-stage → 0.2.36

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/LICENSE +202 -0
  2. package/README.md +309 -2
  3. package/_dist/comp.d.ts +9 -0
  4. package/_dist/comp.d.ts.map +1 -0
  5. package/_dist/earlier.d.ts +108 -0
  6. package/_dist/earlier.d.ts.map +1 -0
  7. package/_dist/graph.d.ts +13 -0
  8. package/_dist/graph.d.ts.map +1 -0
  9. package/_dist/inspect.d.ts +28 -0
  10. package/_dist/inspect.d.ts.map +1 -0
  11. package/_dist/mod.d.ts +54 -0
  12. package/_dist/mod.d.ts.map +1 -0
  13. package/_dist/passage.d.ts +19 -0
  14. package/_dist/passage.d.ts.map +1 -0
  15. package/_dist/recall.d.ts +67 -0
  16. package/_dist/recall.d.ts.map +1 -0
  17. package/_dist/save.d.ts +45 -0
  18. package/_dist/save.d.ts.map +1 -0
  19. package/_dist/tools.d.ts +12 -0
  20. package/_dist/tools.d.ts.map +1 -0
  21. package/_dist/views.d.ts +17 -0
  22. package/_dist/views.d.ts.map +1 -0
  23. package/_dist/vocab.d.ts +7 -0
  24. package/_dist/vocab.d.ts.map +1 -0
  25. package/around.js +141 -0
  26. package/around.js.map +1 -0
  27. package/around.ts +152 -0
  28. package/comp.js +42 -0
  29. package/comp.js.map +1 -0
  30. package/comp.ts +45 -0
  31. package/deno.json +1 -0
  32. package/earlier.js +386 -0
  33. package/earlier.js.map +1 -0
  34. package/earlier.ts +494 -0
  35. package/graph.js +138 -0
  36. package/graph.js.map +1 -0
  37. package/graph.ts +133 -0
  38. package/inspect.js +168 -0
  39. package/inspect.js.map +1 -0
  40. package/inspect.ts +169 -0
  41. package/mod.js +54 -0
  42. package/mod.js.map +1 -0
  43. package/mod.ts +55 -0
  44. package/package.json +51 -4
  45. package/passage.js +67 -0
  46. package/passage.js.map +1 -0
  47. package/passage.ts +75 -0
  48. package/recall.js +145 -0
  49. package/recall.js.map +1 -0
  50. package/recall.ts +180 -0
  51. package/save.js +93 -0
  52. package/save.js.map +1 -0
  53. package/save.ts +113 -0
  54. package/tools.js +246 -0
  55. package/tools.js.map +1 -0
  56. package/tools.ts +250 -0
  57. package/views.js +18 -0
  58. package/views.js.map +1 -0
  59. package/views.ts +23 -0
  60. package/vocab.js +14 -0
  61. package/vocab.js.map +1 -0
  62. package/vocab.json +456 -0
  63. package/vocab.ts +16 -0
package/save.ts ADDED
@@ -0,0 +1,113 @@
1
+ // Writing one down. A memory is a mark on the entity holding what somebody
2
+ // said: {@link marked} puts it on an entity that already holds the words (a
3
+ // session entry, a comment, a doc), and {@link saved} makes a doc to hold words
4
+ // the graph has nowhere yet. Neither edits words that are already there.
5
+ //
6
+ // Two rules live here, and both are about keeping the person's words the
7
+ // person's words.
8
+ //
9
+ // An empty `said` is rejected. A memory with no sentence in it is an agent's
10
+ // note about a conversation, which is the thing this whole package exists to
11
+ // not be.
12
+ //
13
+ // The context is truncated to two lines. Context is what somebody needs in order
14
+ // to read the sentence — what was being talked about, which app, which
15
+ // afternoon — and left unbounded it grows into the summary the sentence was
16
+ // saved instead of. Two lines is enough to say "we were looking at the recipe
17
+ // app" and not enough to restate what was said.
18
+
19
+ import type { Bundle, Eid } from 'jsr:@yaks/graph@0.2.36'
20
+ import { Refused } from '@yaks/graph/errors'
21
+ import { MEMORY } from './comp.js'
22
+
23
+ /** The most context a memory carries, in lines. */
24
+ export let LINES = 2
25
+
26
+ /** Why a save was rejected, worded so an agent can fix it. */
27
+ export let EMPTY =
28
+ 'said: the words the person used, as they used them — a memory is their ' +
29
+ 'sentence, never your summary of it'
30
+
31
+ /**
32
+ * The context, truncated: blank lines dropped, each line trimmed,
33
+ * {@link LINES} kept.
34
+ *
35
+ * ```ts
36
+ * clamped(' we were looking at\n\nthe recipe app\nand also this\nand this')
37
+ * // 'we were looking at\nthe recipe app'
38
+ * ```
39
+ */
40
+ export let clamped = (context: string): string =>
41
+ context.split('\n').map((l) => l.trim()).filter(Boolean)
42
+ .slice(0, LINES).join('\n')
43
+
44
+ /** What a caller hands over to mark words the graph already holds. All of it
45
+ * but the entity is about where the words belong: a graph with no spaces in it
46
+ * keeps memories all the same. */
47
+ export type Marking = {
48
+ /** the entity holding the words */
49
+ eid: Eid
50
+ /** the space they belong to */
51
+ space?: Eid
52
+ /** the project they belong to — absent for a principle everybody carries */
53
+ scope?: Eid
54
+ /** who gave the correction, when the words are one; `true` where they are
55
+ * feedback and nobody knows whose */
56
+ feedback?: Eid | true
57
+ /** the line or two needed to read them */
58
+ context?: string
59
+ /** the app they were about, by slug */
60
+ about?: string
61
+ }
62
+
63
+ /** What a caller hands over to keep words the graph holds nowhere yet. */
64
+ export type Saving = Marking & {
65
+ /** the person's own words, verbatim */
66
+ said: string
67
+ /** the index line a recall shows first, where somebody gave one */
68
+ title?: string
69
+ }
70
+
71
+ /** The component marking a memory as a correction somebody gave. */
72
+ export let FEEDBACK = 'feedback'
73
+
74
+ /**
75
+ * A mark on an entity that already holds the words, as the bundles
76
+ * that write it: `memory` and, for a correction, `feedback`, and nothing
77
+ * about the words themselves. Who marked it, and when, the graph stamps.
78
+ *
79
+ * ```ts
80
+ * marked({ eid: 'e1', context: 'looking at the recipe app' })
81
+ * // [{ entity: { eid: 'e1' },
82
+ * // memory: { context: 'looking at the recipe app' } }]
83
+ * ```
84
+ */
85
+ export let marked = (m: Marking): Bundle[] => {
86
+ let context = clamped(m.context ?? '')
87
+ let about = (m.about ?? '').trim()
88
+ return [{
89
+ entity: { eid: m.eid },
90
+ [MEMORY]: {
91
+ ...(m.space ? { space: m.space } : {}),
92
+ ...(m.scope ? { scope: m.scope } : {}),
93
+ ...(context ? { context } : {}),
94
+ ...(about ? { about } : {}),
95
+ },
96
+ ...(m.feedback
97
+ ? { [FEEDBACK]: m.feedback === true ? {} : { by: m.feedback } }
98
+ : {}),
99
+ }]
100
+ }
101
+
102
+ /**
103
+ * Words the graph holds nowhere yet, as the bundles that keep them:
104
+ * a doc whose body is the words exactly as they were said, marked. The byline
105
+ * is stamped by the graph, so nothing here writes one.
106
+ */
107
+ export let saved = (m: Saving): Bundle[] => {
108
+ let said = m.said.trim()
109
+ if (!said) throw new Refused(EMPTY)
110
+ let title = (m.title ?? '').trim()
111
+ let [mark] = marked(m)
112
+ return [{ ...mark, doc: { ...(title ? { title } : {}), body: said } }]
113
+ }
package/tools.js ADDED
@@ -0,0 +1,246 @@
1
+ // What anybody may ask of a memory: the `@yaks/memory/tools` entry point — the
2
+ // implementations behind the `tool: true` declarations in ./vocab.json. Two of
3
+ // them are one loop: keep what somebody said, and get it back the next time it
4
+ // matters. A third finds where somebody said words, the place a save marks;
5
+ // the rest read around a memory (./around.ts). Finding and making the topics
6
+ // beliefs are about is @yaks/topic's.
7
+ //
8
+ // Keeping marks. What somebody said is usually in the graph already — what they
9
+ // typed is a transcript entry, what they wrote is a comment or a doc — so a
10
+ // save marks that entity rather than copying the words into a new one: the
11
+ // entity it names with `on`, or, where it says who said them, the earliest
12
+ // one that person wrote holding the words verbatim. Only words it cannot place
13
+ // become a doc of their own.
14
+ //
15
+ // The loop is why the read returns A token. A memory made to hold words is
16
+ // edited by replacing them, and words replaced by somebody who never read the
17
+ // ones already there is a lost update — the one failure a fleet of agents
18
+ // writing to one graph produces on its own. So a recall returns each memory
19
+ // with a `$was` field, the graph's own way of recording "this is what it held
20
+ // when I read it" (@yaks/graph ./guard.ts), and a save that replaces words must
21
+ // pass that token back. The words a mark sits on are what happened where they
22
+ // were said, and no save replaces them.
23
+ //
24
+ // Nothing here ranks. Words are ranked by meaning where the host keeps vectors
25
+ // of its text (@yaks/host `meaning`): it names the memories nearest them among
26
+ // those the rest of the recall admits, and the store reads those, so a rank
27
+ // never decides what a caller may read. Where it keeps none, or it names none
28
+ // (a memory saved a moment ago, not embedded yet), `line()` (./recall.ts)
29
+ // builds the query string and the store answers it: its full-text index
30
+ // selects the memories containing every word, newest first. A `near` is ranked
31
+ // by the store's vectors in that query string, and the words then select. An
32
+ // index that fails is a worse order, never a failed recall: the host hears of
33
+ // it, and the words select.
34
+ import { line as q, sub } from "@yaks/query";
35
+ import { argsOf } from "@yaks/graph/call";
36
+ import { Refused } from "@yaks/graph/errors";
37
+ import { guarded, witnessed } from "@yaks/doc";
38
+ export { witnessed } from "@yaks/doc";
39
+ import { MEMORY } from "./comp.js";
40
+ import { EMPTY, FEEDBACK, marked, saved } from "./save.js";
41
+ import { line, ordered, terms, words } from "./recall.js";
42
+ import { around } from "./around.js";
43
+ /** How many memories a recall returns when the caller gave no limit. */ export let LIMIT = 8;
44
+ // How many entities holding the words a save looks through for the one to
45
+ // mark: the earliest few, since the first place words were said comes before
46
+ // every place they were quoted.
47
+ let LOOK = 20;
48
+ /** Why a save that would overwrite unread words is rejected: how to get the
49
+ * token it is missing, and why that token is not in this message. */ export let unread = (id)=>`saving over ${id} replaces the words it holds, so it needs the words you ` + `started from. Recall it, merge your change into what it holds, and pass ` + `the was: token that came back with it. The token is not in this message ` + `on purpose: words you have not read are words you would overwrite.`;
50
+ let str = (v)=>v == null ? '' : String(v);
51
+ let comp = (b, name)=>b?.[name] ?? {};
52
+ let ids = (v)=>Array.isArray(v) ? v.map(str).filter(Boolean) : [];
53
+ // Words compared as written, but for how they were wrapped: a line break an
54
+ // importer or an agent put in is not a different sentence.
55
+ let flat = (s)=>s.replace(/\s+/g, ' ').trim();
56
+ // A memory as it stands right now, for a patch to be judged against: the
57
+ // entity the caller named, or nothing where it names no memory of this graph.
58
+ let held = async (graph, eid, space)=>(await graph.read(q`.entity.eid=${eid}&.${MEMORY}${sub(space ? q`.space=${space}` : q``)}&*`))[0];
59
+ // Where the graph already holds what `by` said: the earliest entity they
60
+ // wrote whose text holds the words verbatim. Only the speaker's own: the same
61
+ // words in anybody else's text are a quote of them, and a doc edited to quote
62
+ // them can be older than the words themselves. The store's full-text index
63
+ // finds the entities holding the phrase, and the words are then compared as
64
+ // written.
65
+ let holding = async (graph, said, by, space)=>{
66
+ let phrase = terms(said);
67
+ if (!phrase) return undefined;
68
+ let found = await graph.read(q`${phrase}&.created.by=${by}${sub(space ? q`&.${MEMORY}.space=${space}` : q``)}&*&.order=created.at&.limit=${LOOK}`);
69
+ let want = flat(said);
70
+ return found.find((b)=>flat(words(b)).includes(want));
71
+ };
72
+ // The memories nearest the words in meaning, among those `asked` admits
73
+ // without them, closest first: none where the host keeps no vectors.
74
+ let nearest = async (host, asked)=>{
75
+ if (!host.meaning) return [];
76
+ try {
77
+ let within = line({
78
+ ...asked,
79
+ said: ''
80
+ });
81
+ let hits = await host.meaning(asked.said, {
82
+ limit: asked.limit,
83
+ within
84
+ });
85
+ return hits.map((h)=>h.entity);
86
+ } catch (e) {
87
+ if (!host.report) throw e;
88
+ await host.report(e);
89
+ return [];
90
+ }
91
+ };
92
+ /** The implementations of the tools ./vocab.json declares. A factory, like
93
+ * every other entry point in these packages. A host sharing a graph between
94
+ * spaces binds saves and recalls to one space through its options. */ export let runs = (host = {}, { space } = {})=>({
95
+ memory_save: async (call, graph)=>{
96
+ let args = argsOf(call);
97
+ let named = str(args.id);
98
+ let scope = str(args.scope);
99
+ let feedback = args.feedback;
100
+ let by = str(feedback);
101
+ let where = {
102
+ ...space ? {
103
+ space
104
+ } : {},
105
+ ...scope ? {
106
+ scope
107
+ } : {},
108
+ context: str(args.context),
109
+ about: str(args.about),
110
+ ...feedback == null ? {} : {
111
+ feedback: by || true
112
+ }
113
+ };
114
+ if (!named) {
115
+ let said = str(args.said).trim();
116
+ let on = str(args.on);
117
+ let at = on ? space ? await held(graph, on, space) : (await graph.get([
118
+ on
119
+ ]))[0] : said && by ? await holding(graph, said, by, space) : undefined;
120
+ if (on && !at) {
121
+ throw new Refused(space ? `no memory: ${on}` : `nothing is ${on}`);
122
+ }
123
+ if (on && !words(at)) throw new Refused(`${on} holds no words`);
124
+ if (on && said && !flat(words(at)).includes(flat(said))) {
125
+ throw new Refused(`${on} does not hold those words: ${said}`);
126
+ }
127
+ if (at) return marked({
128
+ eid: at.entity.eid,
129
+ ...where
130
+ });
131
+ if (!said) throw new Refused(EMPTY);
132
+ return saved({
133
+ eid: '$memory',
134
+ said,
135
+ title: str(args.title),
136
+ ...where
137
+ });
138
+ }
139
+ let was = await held(graph, named, space);
140
+ if (!was) throw new Refused(`no memory: ${named}`);
141
+ // The words, and the one precondition that matters. A patch that leaves
142
+ // them alone needs no token; one that replaces words the memory actually
143
+ // holds must pass the token for the words it held. Words a memory marks on
144
+ // something more than itself — a comment, an entry, a task — are what
145
+ // happened there, and are never replaced.
146
+ let doc = {};
147
+ if (args.title != null) doc.title = str(args.title);
148
+ if (args.said != null) doc.body = str(args.said);
149
+ let said = args.said != null;
150
+ if (said && graph.vocab.kindOf(was) != MEMORY) {
151
+ throw new Refused(`${named} is a mark on what was said there, and a memory never ` + 'replaces those words');
152
+ }
153
+ if (said && comp(was, 'doc').body != null && !args.was) {
154
+ throw new Refused(unread(named));
155
+ }
156
+ let memory = {};
157
+ if (scope) memory.scope = scope;
158
+ if (args.context != null) memory.context = str(args.context);
159
+ if (args.about != null) memory.about = str(args.about);
160
+ return [
161
+ guarded({
162
+ entity: {
163
+ eid: named
164
+ },
165
+ ...Object.keys(doc).length ? {
166
+ doc
167
+ } : {},
168
+ ...Object.keys(memory).length ? {
169
+ [MEMORY]: memory
170
+ } : {},
171
+ ...feedback == null ? {} : {
172
+ [FEEDBACK]: by ? {
173
+ by
174
+ } : {}
175
+ }
176
+ }, said ? str(args.was) || null : undefined)
177
+ ];
178
+ },
179
+ memory_recall: async (call, graph)=>{
180
+ let args = argsOf(call);
181
+ let named = ids(args.ids);
182
+ let near = str(args.near);
183
+ let scope = str(args.scope);
184
+ let asked = {
185
+ limit: Number(args.limit ?? LIMIT),
186
+ ...space ? {
187
+ space
188
+ } : {},
189
+ said: str(args.said),
190
+ ...near ? {
191
+ near
192
+ } : {},
193
+ ...scope ? {
194
+ scope
195
+ } : {},
196
+ ...args.feedback ? {
197
+ feedback: true
198
+ } : {},
199
+ ...named.length ? {
200
+ eids: named
201
+ } : {}
202
+ };
203
+ let ranked = asked.said?.trim() && !near && !named.length ? await nearest(host, asked) : [];
204
+ let read = async (a)=>(await graph.read(line(a))).map(witnessed);
205
+ return ranked.length ? ordered(ranked, await read({
206
+ ...asked,
207
+ said: '',
208
+ eids: ranked
209
+ })) : await read(asked);
210
+ },
211
+ // A memory made to hold words is trashed whole; a mark leaves the words
212
+ // where they were said and takes only itself away. Both leave by the
213
+ // store's trash, so nothing forgotten is erased.
214
+ memory_forget: async (call, graph)=>{
215
+ let named = str(argsOf(call).id);
216
+ let was = await held(graph, named, space);
217
+ if (!was) throw new Refused(`no memory: ${named}`);
218
+ let entity = {
219
+ eid: was.entity.eid
220
+ };
221
+ return [
222
+ graph.vocab.kindOf(was) == MEMORY ? {
223
+ entity,
224
+ $delete: true
225
+ } : {
226
+ entity,
227
+ [MEMORY]: null,
228
+ [FEEDBACK]: null
229
+ }
230
+ ];
231
+ },
232
+ memory_source: async (call, graph)=>{
233
+ let args = argsOf(call);
234
+ let said = str(args.said);
235
+ let by = str(args.by);
236
+ let found = await holding(graph, said, by, space);
237
+ if (!found) {
238
+ throw new Refused(`nothing ${by} wrote holds those words: ${said}`);
239
+ }
240
+ return [
241
+ found
242
+ ];
243
+ },
244
+ ...around
245
+ });
246
+ //# sourceMappingURL=tools.js.map
package/tools.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sources":["./tools.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,4EAA4E;AAC5E,6EAA6E;AAC7E,sCAAsC;AACtC,EAAE;AACF,gFAAgF;AAChF,4EAA4E;AAC5E,2EAA2E;AAC3E,2EAA2E;AAC3E,+EAA+E;AAC/E,6BAA6B;AAC7B,EAAE;AACF,2EAA2E;AAC3E,8EAA8E;AAC9E,0EAA0E;AAC1E,4EAA4E;AAC5E,8EAA8E;AAC9E,gFAAgF;AAChF,8EAA8E;AAC9E,wCAAwC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OAAO;QACL,MAAM,KAAK,CAAC,MAAM,CAAC,QAAQ,SACvB;UAAE;UAAQ,SAAS;QAAK,IACxB;UAAE;UAAQ,CAAC,OAAO,EAAE;UAAM,CAAC,SAAS,EAAE;QAAK;OAChD;IACH;IAEA,eAAe,OAAO,MAAM;MAC1B,IAAI,OAAO,OAAO;MAClB,IAAI,OAAO,IAAI,KAAK,IAAI;MACxB,IAAI,KAAK,IAAI,KAAK,EAAE;MACpB,IAAI,QAAQ,MAAM,QAAQ,OAAO,MAAM,IAAI;MAC3C,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,QAAQ,CAAC,QAAQ,EAAE,GAAG,0BAA0B,EAAE,MAAM;MACpE;MACA,OAAO;QAAC;OAAM;IAChB;IAEA,GAAG,MAAM;EACX,CAAC,EAAC"}
package/tools.ts ADDED
@@ -0,0 +1,250 @@
1
+ // What anybody may ask of a memory: the `@yaks/memory/tools` entry point — the
2
+ // implementations behind the `tool: true` declarations in ./vocab.json. Two of
3
+ // them are one loop: keep what somebody said, and get it back the next time it
4
+ // matters. A third finds where somebody said words, the place a save marks;
5
+ // the rest read around a memory (./around.ts). Finding and making the topics
6
+ // beliefs are about is @yaks/topic's.
7
+ //
8
+ // Keeping marks. What somebody said is usually in the graph already — what they
9
+ // typed is a transcript entry, what they wrote is a comment or a doc — so a
10
+ // save marks that entity rather than copying the words into a new one: the
11
+ // entity it names with `on`, or, where it says who said them, the earliest
12
+ // one that person wrote holding the words verbatim. Only words it cannot place
13
+ // become a doc of their own.
14
+ //
15
+ // The loop is why the read returns A token. A memory made to hold words is
16
+ // edited by replacing them, and words replaced by somebody who never read the
17
+ // ones already there is a lost update — the one failure a fleet of agents
18
+ // writing to one graph produces on its own. So a recall returns each memory
19
+ // with a `$was` field, the graph's own way of recording "this is what it held
20
+ // when I read it" (@yaks/graph ./guard.ts), and a save that replaces words must
21
+ // pass that token back. The words a mark sits on are what happened where they
22
+ // were said, and no save replaces them.
23
+ //
24
+ // Nothing here ranks. Words are ranked by meaning where the host keeps vectors
25
+ // of its text (@yaks/host `meaning`): it names the memories nearest them among
26
+ // those the rest of the recall admits, and the store reads those, so a rank
27
+ // never decides what a caller may read. Where it keeps none, or it names none
28
+ // (a memory saved a moment ago, not embedded yet), `line()` (./recall.ts)
29
+ // builds the query string and the store answers it: its full-text index
30
+ // selects the memories containing every word, newest first. A `near` is ranked
31
+ // by the store's vectors in that query string, and the words then select. An
32
+ // index that fails is a worse order, never a failed recall: the host hears of
33
+ // it, and the words select.
34
+
35
+ import type { Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
36
+ import { line as q, sub } from '@yaks/query'
37
+ import { argsOf } from '@yaks/graph/call'
38
+ import { Refused } from '@yaks/graph/errors'
39
+ import { guarded, witnessed } from '@yaks/doc'
40
+ export { witnessed } from '@yaks/doc'
41
+ import type { Runs } from 'jsr:@yaks/graph@0.2.36/tools'
42
+ import type { Host } from 'jsr:@yaks/host@0.2.36'
43
+ import { MEMORY } from './comp.js'
44
+ import { EMPTY, FEEDBACK, marked, type Marking, saved } from './save.js'
45
+ import { type Asked, line, ordered, terms, words } from './recall.js'
46
+ import { around } from './around.js'
47
+
48
+ /** How many memories a recall returns when the caller gave no limit. */
49
+ export let LIMIT = 8
50
+
51
+ // How many entities holding the words a save looks through for the one to
52
+ // mark: the earliest few, since the first place words were said comes before
53
+ // every place they were quoted.
54
+ let LOOK = 20
55
+
56
+ /** Why a save that would overwrite unread words is rejected: how to get the
57
+ * token it is missing, and why that token is not in this message. */
58
+ export let unread = (id: string): string =>
59
+ `saving over ${id} replaces the words it holds, so it needs the words you ` +
60
+ `started from. Recall it, merge your change into what it holds, and pass ` +
61
+ `the was: token that came back with it. The token is not in this message ` +
62
+ `on purpose: words you have not read are words you would overwrite.`
63
+
64
+ let str = (v: unknown): string => v == null ? '' : String(v)
65
+
66
+ let comp = (b: Bundle | undefined, name: string): Comp =>
67
+ (b?.[name] ?? {}) as Comp
68
+
69
+ let ids = (v: unknown): string[] =>
70
+ Array.isArray(v) ? v.map(str).filter(Boolean) : []
71
+
72
+ // Words compared as written, but for how they were wrapped: a line break an
73
+ // importer or an agent put in is not a different sentence.
74
+ let flat = (s: string) => s.replace(/\s+/g, ' ').trim()
75
+
76
+ // A memory as it stands right now, for a patch to be judged against: the
77
+ // entity the caller named, or nothing where it names no memory of this graph.
78
+ let held = async (
79
+ graph: Graph,
80
+ eid: string,
81
+ space?: string,
82
+ ): Promise<Bundle | undefined> =>
83
+ (await graph.read(
84
+ q`.entity.eid=${eid}&.${MEMORY}${sub(space ? q`.space=${space}` : q``)}&*`,
85
+ ))[0]
86
+
87
+ // Where the graph already holds what `by` said: the earliest entity they
88
+ // wrote whose text holds the words verbatim. Only the speaker's own: the same
89
+ // words in anybody else's text are a quote of them, and a doc edited to quote
90
+ // them can be older than the words themselves. The store's full-text index
91
+ // finds the entities holding the phrase, and the words are then compared as
92
+ // written.
93
+ let holding = async (
94
+ graph: Pick<Graph, 'read'>,
95
+ said: string,
96
+ by: string,
97
+ space?: string,
98
+ ): Promise<Bundle | undefined> => {
99
+ let phrase = terms(said)
100
+ if (!phrase) return undefined
101
+ let found = await graph.read(
102
+ q`${phrase}&.created.by=${by}${
103
+ sub(space ? q`&.${MEMORY}.space=${space}` : q``)
104
+ }&*&.order=created.at&.limit=${LOOK}`,
105
+ )
106
+ let want = flat(said)
107
+ return found.find((b) => flat(words(b)).includes(want))
108
+ }
109
+
110
+ /** What a recall asks of its host: words ranked by meaning, where it keeps
111
+ * vectors, and where to say that ranking failed. */
112
+ export type Ranking = Partial<Pick<Host, 'meaning' | 'report'>>
113
+
114
+ // The memories nearest the words in meaning, among those `asked` admits
115
+ // without them, closest first: none where the host keeps no vectors.
116
+ let nearest = async (host: Ranking, asked: Asked): Promise<string[]> => {
117
+ if (!host.meaning) return []
118
+ try {
119
+ let within = line({ ...asked, said: '' })
120
+ let hits = await host.meaning(asked.said!, { limit: asked.limit, within })
121
+ return hits.map((h) => h.entity)
122
+ } catch (e) {
123
+ if (!host.report) throw e
124
+ await host.report(e)
125
+ return []
126
+ }
127
+ }
128
+
129
+ /** The implementations of the tools ./vocab.json declares. A factory, like
130
+ * every other entry point in these packages. A host sharing a graph between
131
+ * spaces binds saves and recalls to one space through its options. */
132
+ export let runs = (
133
+ host: Ranking = {},
134
+ { space }: { space?: string } = {},
135
+ ): Runs => ({
136
+ memory_save: async (call, graph): Promise<Bundle[]> => {
137
+ let args = argsOf(call)
138
+ let named = str(args.id)
139
+ let scope = str(args.scope)
140
+ let feedback = args.feedback
141
+ let by = str(feedback)
142
+ let where: Omit<Marking, 'eid'> = {
143
+ ...(space ? { space } : {}),
144
+ ...(scope ? { scope } : {}),
145
+ context: str(args.context),
146
+ about: str(args.about),
147
+ ...(feedback == null ? {} : { feedback: by || true }),
148
+ }
149
+ if (!named) {
150
+ let said = str(args.said).trim()
151
+ let on = str(args.on)
152
+ let at = on
153
+ ? space ? await held(graph, on, space) : (await graph.get([on]))[0]
154
+ : said && by
155
+ ? await holding(graph, said, by, space)
156
+ : undefined
157
+ if (on && !at) {
158
+ throw new Refused(space ? `no memory: ${on}` : `nothing is ${on}`)
159
+ }
160
+ if (on && !words(at!)) throw new Refused(`${on} holds no words`)
161
+ if (on && said && !flat(words(at!)).includes(flat(said))) {
162
+ throw new Refused(`${on} does not hold those words: ${said}`)
163
+ }
164
+ if (at) return marked({ eid: at.entity.eid, ...where })
165
+ if (!said) throw new Refused(EMPTY)
166
+ return saved({ eid: '$memory', said, title: str(args.title), ...where })
167
+ }
168
+ let was = await held(graph, named, space)
169
+ if (!was) throw new Refused(`no memory: ${named}`)
170
+ // The words, and the one precondition that matters. A patch that leaves
171
+ // them alone needs no token; one that replaces words the memory actually
172
+ // holds must pass the token for the words it held. Words a memory marks on
173
+ // something more than itself — a comment, an entry, a task — are what
174
+ // happened there, and are never replaced.
175
+ let doc: Comp = {}
176
+ if (args.title != null) doc.title = str(args.title)
177
+ if (args.said != null) doc.body = str(args.said)
178
+ let said = args.said != null
179
+ if (said && graph.vocab.kindOf(was) != MEMORY) {
180
+ throw new Refused(
181
+ `${named} is a mark on what was said there, and a memory never ` +
182
+ 'replaces those words',
183
+ )
184
+ }
185
+ if (said && comp(was, 'doc').body != null && !args.was) {
186
+ throw new Refused(unread(named))
187
+ }
188
+ let memory: Comp = {}
189
+ if (scope) memory.scope = scope
190
+ if (args.context != null) memory.context = str(args.context)
191
+ if (args.about != null) memory.about = str(args.about)
192
+ return [guarded({
193
+ entity: { eid: named },
194
+ ...(Object.keys(doc).length ? { doc } : {}),
195
+ ...(Object.keys(memory).length ? { [MEMORY]: memory } : {}),
196
+ ...(feedback == null ? {} : { [FEEDBACK]: by ? { by } : {} }),
197
+ }, said ? str(args.was) || null : undefined)]
198
+ },
199
+
200
+ memory_recall: async (call, graph): Promise<Bundle[]> => {
201
+ let args = argsOf(call)
202
+ let named = ids(args.ids)
203
+ let near = str(args.near)
204
+ let scope = str(args.scope)
205
+ let asked: Asked = {
206
+ limit: Number(args.limit ?? LIMIT),
207
+ ...(space ? { space } : {}),
208
+ said: str(args.said),
209
+ ...(near ? { near } : {}),
210
+ ...(scope ? { scope } : {}),
211
+ ...(args.feedback ? { feedback: true } : {}),
212
+ ...(named.length ? { eids: named } : {}),
213
+ }
214
+ let ranked = asked.said?.trim() && !near && !named.length
215
+ ? await nearest(host, asked)
216
+ : []
217
+ let read = async (a: Asked) => (await graph.read(line(a))).map(witnessed)
218
+ return ranked.length
219
+ ? ordered(ranked, await read({ ...asked, said: '', eids: ranked }))
220
+ : await read(asked)
221
+ },
222
+
223
+ // A memory made to hold words is trashed whole; a mark leaves the words
224
+ // where they were said and takes only itself away. Both leave by the
225
+ // store's trash, so nothing forgotten is erased.
226
+ memory_forget: async (call, graph): Promise<Bundle[]> => {
227
+ let named = str(argsOf(call).id)
228
+ let was = await held(graph, named, space)
229
+ if (!was) throw new Refused(`no memory: ${named}`)
230
+ let entity = { eid: was.entity.eid }
231
+ return [
232
+ graph.vocab.kindOf(was) == MEMORY
233
+ ? { entity, $delete: true }
234
+ : { entity, [MEMORY]: null, [FEEDBACK]: null },
235
+ ]
236
+ },
237
+
238
+ memory_source: async (call, graph): Promise<Bundle[]> => {
239
+ let args = argsOf(call)
240
+ let said = str(args.said)
241
+ let by = str(args.by)
242
+ let found = await holding(graph, said, by, space)
243
+ if (!found) {
244
+ throw new Refused(`nothing ${by} wrote holds those words: ${said}`)
245
+ }
246
+ return [found]
247
+ },
248
+
249
+ ...around,
250
+ })
package/views.js ADDED
@@ -0,0 +1,18 @@
1
+ // The inspector's belief page is loaded only by the interface that draws
2
+ // it. A portable printer reads this facet without loading UI.
3
+ /** How many turns either side of a cited one a belief's page shows. */ export let AROUND = {
4
+ before: 3,
5
+ after: 2
6
+ };
7
+ /**
8
+ * What a belief states, without the words it quotes: its body up to the
9
+ * first quote.
10
+ *
11
+ * ```ts
12
+ * import { statement } from './views.ts'
13
+ * statement('Tests never share a lock.\n\n> never share a lock\n(Jeff)')
14
+ * // 'Tests never share a lock.'
15
+ * ```
16
+ */ export let statement = (body)=>body.split(/\n\s*\n|\n>/)[0].trim();
17
+ /** The inspector's domain pages and parts. */ export let inspectViews = ()=>import("./inspect.js").then((m)=>m.inspectViews);
18
+ //# sourceMappingURL=views.js.map
package/views.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.js","sources":["./views.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,8DAA8D;AAG9D,qEAAqE,GACrE,OAAO,IAAI,SAAS;EAAE,QAAQ;EAAG,OAAO;AAAE,EAAC;AAE3C;;;;;;;;;CASC,GACD,OAAO,IAAI,YAAY,CAAC,OACtB,KAAK,KAAK,CAAC,cAAc,CAAC,EAAE,CAAC,IAAI,GAAE;AAErC,4CAA4C,GAC5C,OAAO,IAAI,eAAe,IACxB,MAAM,CAAC,gBAAgB,IAAI,CAAC,CAAC,IAAM,EAAE,YAAY,EAAC"}
package/views.ts ADDED
@@ -0,0 +1,23 @@
1
+ // The inspector's belief page is loaded only by the interface that draws
2
+ // it. A portable printer reads this facet without loading UI.
3
+ import type { View } from 'jsr:@yaks/inspect@0.2.36'
4
+
5
+ /** How many turns either side of a cited one a belief's page shows. */
6
+ export let AROUND = { before: 3, after: 2 }
7
+
8
+ /**
9
+ * What a belief states, without the words it quotes: its body up to the
10
+ * first quote.
11
+ *
12
+ * ```ts
13
+ * import { statement } from './views.ts'
14
+ * statement('Tests never share a lock.\n\n> never share a lock\n(Jeff)')
15
+ * // 'Tests never share a lock.'
16
+ * ```
17
+ */
18
+ export let statement = (body: string): string =>
19
+ body.split(/\n\s*\n|\n>/)[0].trim()
20
+
21
+ /** The inspector's domain pages and parts. */
22
+ export let inspectViews = (): Promise<View[]> =>
23
+ import('./inspect.js').then((m) => m.inspectViews)