@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/passage.js ADDED
@@ -0,0 +1,67 @@
1
+ // What every agent reads at the start of every conversation: the person's own
2
+ // sentences, newest first, under one heading per space.
3
+ //
4
+ // Bounded, because it is paid for on every connection — {@link LAST} of them
5
+ // and {@link BYTES} bytes, whichever runs out first, and then a line saying
6
+ // that there are more and which tool returns the rest. A person who has said
7
+ // forty things is not owed forty of them at the top of every context; they are
8
+ // owed the last few and a way to reach the others.
9
+ //
10
+ // Each entry is the sentence, whole and in quotes, with its context indented
11
+ // under it. Whole, because half of what somebody said is worse than none of it
12
+ // — a snippet is for finding a thing, and this is the thing.
13
+ /** The most memories a passage shows. */ export let LAST = 8;
14
+ /** The most bytes it spends on them. */ export let BYTES = 2048;
15
+ let bytes = (s)=>new TextEncoder().encode(s).length;
16
+ // One memory: what was said, then what is needed to read it. A byline only
17
+ // where somebody other than the person the heading names said it — in a space
18
+ // of one, which is most of them, it would be the same name every time.
19
+ let entry = (m, name)=>{
20
+ let said = `"${m.said.trim()}"` + (m.by && m.by != name ? ` — ${m.by}` : '');
21
+ let under = [
22
+ ...m.about ? [
23
+ `about the ${m.about} app`
24
+ ] : [],
25
+ ...m.context ? m.context.split('\n') : []
26
+ ];
27
+ return [
28
+ said,
29
+ ...under.map((l)=>` ${l}`)
30
+ ].join('\n');
31
+ };
32
+ // What is not shown, in one line. Never a count: the passage reads what it can
33
+ // afford and nothing counts the rest, which would mean a second query on every
34
+ // connection to report something the recall tool already answers.
35
+ let MORE = 'There are more — memory_recall finds any of them by what they ' + 'are about.';
36
+ /**
37
+ * One space's memories as the passage renders them, or '' where it has none.
38
+ * `name` is the person the heading is about — whoever said most of them.
39
+ *
40
+ * ```ts
41
+ * // ## What the owner has said
42
+ * // In ada, his own words, newest first…
43
+ * //
44
+ * // "use grams, never cups"
45
+ * // about the recipes app
46
+ * ```
47
+ */ export let passage = (where, held)=>{
48
+ if (!held.length) return '';
49
+ let name = where.name || 'the person';
50
+ let head = `## What ${name} has said\n` + `In ${where.space}, their own words about how they want things done ` + 'here, newest first. When they say how something should be built or ' + 'handled, keep their exact words with memory_save.';
51
+ let out = [];
52
+ let spent = 0;
53
+ for (let m of held.slice(0, LAST)){
54
+ let said = entry(m, name);
55
+ spent += bytes(said);
56
+ if (spent > BYTES && out.length) break;
57
+ out.push(said);
58
+ }
59
+ return [
60
+ head,
61
+ ...out,
62
+ ...held.length > out.length ? [
63
+ MORE
64
+ ] : []
65
+ ].join('\n\n');
66
+ };
67
+ //# sourceMappingURL=passage.js.map
package/passage.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passage.js","sources":["./passage.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,wDAAwD;AACxD,EAAE;AACF,6EAA6E;AAC7E,4EAA4E;AAC5E,6EAA6E;AAC7E,+EAA+E;AAC/E,mDAAmD;AACnD,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,6DAA6D;AAI7D,uCAAuC,GACvC,OAAO,IAAI,OAAO,EAAC;AAEnB,sCAAsC,GACtC,OAAO,IAAI,QAAQ,KAAI;AAEvB,IAAI,QAAQ,CAAC,IAAc,IAAI,cAAc,MAAM,CAAC,GAAG,MAAM;AAE7D,2EAA2E;AAC3E,8EAA8E;AAC9E,uEAAuE;AACvE,IAAI,QAAQ,CAAC,GAAW;EACtB,IAAI,OAAO,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,GAC7B,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,OAAO,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE;EAC3C,IAAI,QAAQ;OACN,EAAE,KAAK,GAAG;MAAC,CAAC,UAAU,EAAE,EAAE,KAAK,CAAC,IAAI,CAAC;KAAC,GAAG,EAAE;OAC3C,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE;GAC3C;EACD,OAAO;IAAC;OAAS,MAAM,GAAG,CAAC,CAAC,IAAM,CAAC,EAAE,EAAE,GAAG;GAAE,CAAC,IAAI,CAAC;AACpD;AAEA,+EAA+E;AAC/E,+EAA+E;AAC/E,kEAAkE;AAClE,IAAI,OAAO,mEACT;AAEF;;;;;;;;;;;CAWC,GACD,OAAO,IAAI,UAAU,CACnB,OACA;EAEA,IAAI,CAAC,KAAK,MAAM,EAAE,OAAO;EACzB,IAAI,OAAO,MAAM,IAAI,IAAI;EACzB,IAAI,OAAO,CAAC,QAAQ,EAAE,KAAK,WAAW,CAAC,GACrC,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC,kDAAkD,CAAC,GACrE,wEACA;EACF,IAAI,MAAgB,EAAE;EACtB,IAAI,QAAQ;EACZ,KAAK,IAAI,KAAK,KAAK,KAAK,CAAC,GAAG,MAAO;IACjC,IAAI,OAAO,MAAM,GAAG;IACpB,SAAS,MAAM;IACf,IAAI,QAAQ,SAAS,IAAI,MAAM,EAAE;IACjC,IAAI,IAAI,CAAC;EACX;EACA,OAAO;IAAC;OAAS;OAAS,KAAK,MAAM,GAAG,IAAI,MAAM,GAAG;MAAC;KAAK,GAAG,EAAE;GAAE,CAC/D,IAAI,CAAC;AACV,EAAC"}
package/passage.ts ADDED
@@ -0,0 +1,75 @@
1
+ // What every agent reads at the start of every conversation: the person's own
2
+ // sentences, newest first, under one heading per space.
3
+ //
4
+ // Bounded, because it is paid for on every connection — {@link LAST} of them
5
+ // and {@link BYTES} bytes, whichever runs out first, and then a line saying
6
+ // that there are more and which tool returns the rest. A person who has said
7
+ // forty things is not owed forty of them at the top of every context; they are
8
+ // owed the last few and a way to reach the others.
9
+ //
10
+ // Each entry is the sentence, whole and in quotes, with its context indented
11
+ // under it. Whole, because half of what somebody said is worse than none of it
12
+ // — a snippet is for finding a thing, and this is the thing.
13
+
14
+ import type { Memory } from './recall.ts'
15
+
16
+ /** The most memories a passage shows. */
17
+ export let LAST = 8
18
+
19
+ /** The most bytes it spends on them. */
20
+ export let BYTES = 2048
21
+
22
+ let bytes = (s: string) => new TextEncoder().encode(s).length
23
+
24
+ // One memory: what was said, then what is needed to read it. A byline only
25
+ // where somebody other than the person the heading names said it — in a space
26
+ // of one, which is most of them, it would be the same name every time.
27
+ let entry = (m: Memory, name: string): string => {
28
+ let said = `"${m.said.trim()}"` +
29
+ (m.by && m.by != name ? ` — ${m.by}` : '')
30
+ let under = [
31
+ ...(m.about ? [`about the ${m.about} app`] : []),
32
+ ...(m.context ? m.context.split('\n') : []),
33
+ ]
34
+ return [said, ...under.map((l) => ` ${l}`)].join('\n')
35
+ }
36
+
37
+ // What is not shown, in one line. Never a count: the passage reads what it can
38
+ // afford and nothing counts the rest, which would mean a second query on every
39
+ // connection to report something the recall tool already answers.
40
+ let MORE = 'There are more — memory_recall finds any of them by what they ' +
41
+ 'are about.'
42
+
43
+ /**
44
+ * One space's memories as the passage renders them, or '' where it has none.
45
+ * `name` is the person the heading is about — whoever said most of them.
46
+ *
47
+ * ```ts
48
+ * // ## What the owner has said
49
+ * // In ada, his own words, newest first…
50
+ * //
51
+ * // "use grams, never cups"
52
+ * // about the recipes app
53
+ * ```
54
+ */
55
+ export let passage = (
56
+ where: { name: string; space: string },
57
+ held: Memory[],
58
+ ): string => {
59
+ if (!held.length) return ''
60
+ let name = where.name || 'the person'
61
+ let head = `## What ${name} has said\n` +
62
+ `In ${where.space}, their own words about how they want things done ` +
63
+ 'here, newest first. When they say how something should be built or ' +
64
+ 'handled, keep their exact words with memory_save.'
65
+ let out: string[] = []
66
+ let spent = 0
67
+ for (let m of held.slice(0, LAST)) {
68
+ let said = entry(m, name)
69
+ spent += bytes(said)
70
+ if (spent > BYTES && out.length) break
71
+ out.push(said)
72
+ }
73
+ return [head, ...out, ...(held.length > out.length ? [MORE] : [])]
74
+ .join('\n\n')
75
+ }
package/recall.js ADDED
@@ -0,0 +1,145 @@
1
+ // Getting them back. A recall answers memories whole — the sentence and its
2
+ // context, never a snippet — because half of what somebody said is worse than
3
+ // none of it. What is ranked is which ones, not how much of them.
4
+ //
5
+ // Several rankings, one result. Where the host keeps vectors of its text, it
6
+ // ranks words by meaning (@yaks/host `meaning`) and the recall tool reads the
7
+ // memories it names in that order (./tools.ts); this package never learns how
8
+ // that is done. A store with vectors also answers `.near=<entity>` in the query
9
+ // string itself (@yaks/embedding), and {@link Asked.near} is where that goes.
10
+ // With neither, the words select: {@link line} builds a query string carrying
11
+ // the words, which every yaks store answers as a full-text search over the text
12
+ // a memory marks — a doc's body, a transcript entry's content — and the newest
13
+ // of the selected rows come first, because a query string carries no bm25
14
+ // score.
15
+ //
16
+ // Every one of those reads is a line, so a quarantined memory — one somebody
17
+ // set aside as harmful to act on (@yaks/kernel `quarantined`) — is left out
18
+ // here, once, and no door that recalls hands it back as if it stood.
19
+ import { line as q, sub } from "@yaks/query";
20
+ import { MEMORY } from "./comp.js";
21
+ // The stamp @yaks/kernel puts on what is set aside as harmful to act on.
22
+ let QUARANTINED = 'quarantined';
23
+ let comp = (b, name)=>b[name] && typeof b[name] == 'object' ? b[name] : {};
24
+ let str = (v)=>typeof v == 'string' ? v : '';
25
+ // A byline reads back as the eid, or as `{eid, name}` where the store resolved
26
+ // the name; either way, what a passage wants is the name when there is one.
27
+ let who = (v)=>v && typeof v == 'object' ? str(v.name) || str(v.eid) : str(v);
28
+ // Where an entity keeps its words, in the order they are looked for: a doc's
29
+ // body (a memory made to hold them, a comment, a task), then a transcript
30
+ // entry's content (@yaks/session), then a doc's title, all a task filed as one
31
+ // line says. Matched by component, never by kind, so a memory marked on
32
+ // anything that holds words reads the same way.
33
+ let HOMES = [
34
+ [
35
+ 'doc',
36
+ 'body'
37
+ ],
38
+ [
39
+ 'content',
40
+ 'body'
41
+ ],
42
+ [
43
+ 'doc',
44
+ 'title'
45
+ ]
46
+ ];
47
+ /**
48
+ * The words an entity holds: a doc's body, else a transcript entry's content,
49
+ * else a doc's title, else ''.
50
+ *
51
+ * ```ts
52
+ * words({ entity: { eid: 'e1' }, content: { body: 'use grams' } })
53
+ * // 'use grams'
54
+ * ```
55
+ */ export let words = (b)=>{
56
+ for (let [c, p] of HOMES){
57
+ let v = b[c]?.[p];
58
+ if (typeof v == 'string' && v) return v;
59
+ }
60
+ return '';
61
+ };
62
+ /** One bundle as a memory. */ export let heard = (b)=>{
63
+ let m = comp(b, MEMORY);
64
+ let created = comp(b, 'created');
65
+ return {
66
+ eid: b.entity.eid,
67
+ said: words(b),
68
+ context: str(m.context),
69
+ about: str(m.about),
70
+ by: who(created.by),
71
+ at: str(created.at)
72
+ };
73
+ };
74
+ /**
75
+ * Words as search terms, stripped of anything the query string cannot carry:
76
+ * its own punctuation (`&`, `=`, `.`) would be read as grammar, and a
77
+ * full-text index matches words anyway.
78
+ *
79
+ * ```ts
80
+ * terms('.doc&how do they like it?')
81
+ * // 'doc how do they like it'
82
+ * ```
83
+ */ export let terms = (said)=>said.replace(/[^\p{L}\p{N}\s'-]+/gu, ' ').trim().replace(/\s+/g, ' ');
84
+ /**
85
+ * The query string that finds memories: with words, the memories containing
86
+ * every one of them, which is what somebody searching means; with a `near`,
87
+ * ranked by meaning; otherwise the newest words first. Words do not rank:
88
+ * @yaks/fts compiles a word into a condition and keeps its bm25 score for the
89
+ * search tool, so a query string carrying words is a filter and the newest
90
+ * still come first. A quarantined memory never comes back. Every component
91
+ * comes back (`*`), since the words may be a doc's body or an entry's content
92
+ * and a row carries only what its query names.
93
+ *
94
+ * ```ts
95
+ * line({ space: 's1', limit: 8 })
96
+ * // '.memory.space=s1&!quarantined&*&.order=-created.at&.limit=8'
97
+ * ```
98
+ */ export let line = (asked)=>{
99
+ let said = terms(asked.said ?? '');
100
+ let ranked = !!(asked.eids?.length || asked.near);
101
+ return [
102
+ // Each word is one text term, quoted where it holds a quote or a dash.
103
+ ...said ? said.split(' ').map((w)=>q`${w}`) : [],
104
+ ...asked.eids?.length ? [
105
+ q`.entity.eid=${asked.eids}`
106
+ ] : [],
107
+ ...asked.near ? [
108
+ q`.near=${asked.near}`
109
+ ] : [],
110
+ // A memory is what is being asked for, so the component is always in the
111
+ // query; naming it with a space bounds the result and names it at once.
112
+ asked.space ? q`.${MEMORY}.space=${asked.space}` : q`.${MEMORY}`,
113
+ q`!${QUARANTINED}`,
114
+ ...asked.scope ? [
115
+ q`.${MEMORY}.scope=${asked.scope}`
116
+ ] : [],
117
+ ...asked.feedback ? [
118
+ q`.feedback`
119
+ ] : [],
120
+ q`*`,
121
+ ...asked.near ? [
122
+ q`.order=similar`
123
+ ] : ranked ? [] : [
124
+ q`.order=-created.at`
125
+ ],
126
+ q`.limit=${asked.limit}`
127
+ ].reduce((all, l)=>q`${sub(all)}&${sub(l)}`);
128
+ };
129
+ /**
130
+ * The bundles a store returned, in the order a ranking named them. A store
131
+ * returns a set; the ranking is the caller's, and an id the store did not
132
+ * return (a memory since deleted, one the caller may not read) drops out.
133
+ *
134
+ * ```ts
135
+ * ordered(['b', 'a'], [{ entity: { eid: 'a' } }, { entity: { eid: 'b' } }])
136
+ * // [{ entity: { eid: 'b' } }, { entity: { eid: 'a' } }]
137
+ * ```
138
+ */ export let ordered = (ids, held)=>{
139
+ let by = new Map(held.map((b)=>[
140
+ b.entity.eid,
141
+ b
142
+ ]));
143
+ return ids.flatMap((id)=>by.get(id) ?? []);
144
+ };
145
+ //# sourceMappingURL=recall.js.map
package/recall.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recall.js","sources":["./recall.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAC9E,kEAAkE;AAClE,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8E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,kBAAkB,CAAC;KAAC;IAC3B,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,CAAC,CAAC;GACzB,CAAC,MAAM,CAAC,CAAC,KAAK,IAAM,CAAC,CAAC,EAAE,IAAI,KAAK,CAAC,EAAE,IAAI,GAAG,CAAC;AAC/C,EAAC;AAED;;;;;;;;;CASC,GACD,OAAO,IAAI,UAAU,CAAC,KAAY;EAChC,IAAI,KAAK,IAAI,IAAI,KAAK,GAAG,CAAC,CAAC,IAAM;MAAC,EAAE,MAAM,CAAC,GAAG;MAAE;KAAE;EAClD,OAAO,IAAI,OAAO,CAAC,CAAC,KAAO,GAAG,GAAG,CAAC,OAAO,EAAE;AAC7C,EAAC"}
package/recall.ts ADDED
@@ -0,0 +1,180 @@
1
+ // Getting them back. A recall answers memories whole — the sentence and its
2
+ // context, never a snippet — because half of what somebody said is worse than
3
+ // none of it. What is ranked is which ones, not how much of them.
4
+ //
5
+ // Several rankings, one result. Where the host keeps vectors of its text, it
6
+ // ranks words by meaning (@yaks/host `meaning`) and the recall tool reads the
7
+ // memories it names in that order (./tools.ts); this package never learns how
8
+ // that is done. A store with vectors also answers `.near=<entity>` in the query
9
+ // string itself (@yaks/embedding), and {@link Asked.near} is where that goes.
10
+ // With neither, the words select: {@link line} builds a query string carrying
11
+ // the words, which every yaks store answers as a full-text search over the text
12
+ // a memory marks — a doc's body, a transcript entry's content — and the newest
13
+ // of the selected rows come first, because a query string carries no bm25
14
+ // score.
15
+ //
16
+ // Every one of those reads is a line, so a quarantined memory — one somebody
17
+ // set aside as harmful to act on (@yaks/kernel `quarantined`) — is left out
18
+ // here, once, and no door that recalls hands it back as if it stood.
19
+
20
+ import type { Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
21
+ import { type Built, line as q, sub } from '@yaks/query'
22
+ import { MEMORY } from './comp.js'
23
+
24
+ // The stamp @yaks/kernel puts on what is set aside as harmful to act on.
25
+ let QUARANTINED = 'quarantined'
26
+
27
+ /** One memory, read back. */
28
+ export type Memory = {
29
+ eid: Eid
30
+ /** the person's own words */
31
+ said: string
32
+ /** the line or two needed to read them, or '' */
33
+ context: string
34
+ /** the app it was about, by slug, or '' */
35
+ about: string
36
+ /** who said it — the name where the store gave one, else their id */
37
+ by: string
38
+ /** when they said it, as the store stamped it */
39
+ at: string
40
+ }
41
+
42
+ let comp = (b: Bundle, name: string): Comp =>
43
+ (b[name] && typeof b[name] == 'object' ? b[name] : {}) as Comp
44
+
45
+ let str = (v: unknown): string => typeof v == 'string' ? v : ''
46
+
47
+ // A byline reads back as the eid, or as `{eid, name}` where the store resolved
48
+ // the name; either way, what a passage wants is the name when there is one.
49
+ let who = (v: unknown): string =>
50
+ v && typeof v == 'object'
51
+ ? str((v as { name?: unknown; eid?: unknown }).name) ||
52
+ str((v as { eid?: unknown }).eid)
53
+ : str(v)
54
+
55
+ // Where an entity keeps its words, in the order they are looked for: a doc's
56
+ // body (a memory made to hold them, a comment, a task), then a transcript
57
+ // entry's content (@yaks/session), then a doc's title, all a task filed as one
58
+ // line says. Matched by component, never by kind, so a memory marked on
59
+ // anything that holds words reads the same way.
60
+ let HOMES: [string, string][] = [
61
+ ['doc', 'body'],
62
+ ['content', 'body'],
63
+ ['doc', 'title'],
64
+ ]
65
+
66
+ /**
67
+ * The words an entity holds: a doc's body, else a transcript entry's content,
68
+ * else a doc's title, else ''.
69
+ *
70
+ * ```ts
71
+ * words({ entity: { eid: 'e1' }, content: { body: 'use grams' } })
72
+ * // 'use grams'
73
+ * ```
74
+ */
75
+ export let words = (b: { [comp: string]: unknown }): string => {
76
+ for (let [c, p] of HOMES) {
77
+ let v = (b[c] as Comp | null | undefined)?.[p]
78
+ if (typeof v == 'string' && v) return v
79
+ }
80
+ return ''
81
+ }
82
+
83
+ /** One bundle as a memory. */
84
+ export let heard = (b: Bundle): Memory => {
85
+ let m = comp(b, MEMORY)
86
+ let created = comp(b, 'created')
87
+ return {
88
+ eid: b.entity.eid,
89
+ said: words(b),
90
+ context: str(m.context),
91
+ about: str(m.about),
92
+ by: who(created.by),
93
+ at: str(created.at),
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Words as search terms, stripped of anything the query string cannot carry:
99
+ * its own punctuation (`&`, `=`, `.`) would be read as grammar, and a
100
+ * full-text index matches words anyway.
101
+ *
102
+ * ```ts
103
+ * terms('.doc&how do they like it?')
104
+ * // 'doc how do they like it'
105
+ * ```
106
+ */
107
+ export let terms = (said: string): string =>
108
+ said.replace(/[^\p{L}\p{N}\s'-]+/gu, ' ').trim().replace(/\s+/g, ' ')
109
+
110
+ /** What a recall is looking for: which memories, and what ranks them. */
111
+ export type Asked = {
112
+ /** at most this many */
113
+ limit: number
114
+ /** the space they were said in */
115
+ space?: Eid
116
+ /** the project they are scoped to */
117
+ scope?: Eid
118
+ /** only the ones recording a correction somebody gave */
119
+ feedback?: boolean
120
+ /** the words to select by — the store's own full-text index */
121
+ said?: string
122
+ /** an entity to rank by meaning instead, where the server has embeddings */
123
+ near?: Eid
124
+ /** particular ones, by id */
125
+ eids?: Eid[]
126
+ }
127
+
128
+ /**
129
+ * The query string that finds memories: with words, the memories containing
130
+ * every one of them, which is what somebody searching means; with a `near`,
131
+ * ranked by meaning; otherwise the newest words first. Words do not rank:
132
+ * @yaks/fts compiles a word into a condition and keeps its bm25 score for the
133
+ * search tool, so a query string carrying words is a filter and the newest
134
+ * still come first. A quarantined memory never comes back. Every component
135
+ * comes back (`*`), since the words may be a doc's body or an entry's content
136
+ * and a row carries only what its query names.
137
+ *
138
+ * ```ts
139
+ * line({ space: 's1', limit: 8 })
140
+ * // '.memory.space=s1&!quarantined&*&.order=-created.at&.limit=8'
141
+ * ```
142
+ */
143
+ export let line = (asked: Asked): Built => {
144
+ let said = terms(asked.said ?? '')
145
+ let ranked = !!(asked.eids?.length || asked.near)
146
+ return [
147
+ // Each word is one text term, quoted where it holds a quote or a dash.
148
+ ...(said ? said.split(' ').map((w) => q`${w}`) : []),
149
+ ...(asked.eids?.length ? [q`.entity.eid=${asked.eids}`] : []),
150
+ ...(asked.near ? [q`.near=${asked.near}`] : []),
151
+ // A memory is what is being asked for, so the component is always in the
152
+ // query; naming it with a space bounds the result and names it at once.
153
+ asked.space ? q`.${MEMORY}.space=${asked.space}` : q`.${MEMORY}`,
154
+ q`!${QUARANTINED}`,
155
+ ...(asked.scope ? [q`.${MEMORY}.scope=${asked.scope}`] : []),
156
+ ...(asked.feedback ? [q`.feedback`] : []),
157
+ q`*`,
158
+ ...(asked.near
159
+ ? [q`.order=similar`]
160
+ : ranked
161
+ ? []
162
+ : [q`.order=-created.at`]),
163
+ q`.limit=${asked.limit}`,
164
+ ].reduce((all, l) => q`${sub(all)}&${sub(l)}`)
165
+ }
166
+
167
+ /**
168
+ * The bundles a store returned, in the order a ranking named them. A store
169
+ * returns a set; the ranking is the caller's, and an id the store did not
170
+ * return (a memory since deleted, one the caller may not read) drops out.
171
+ *
172
+ * ```ts
173
+ * ordered(['b', 'a'], [{ entity: { eid: 'a' } }, { entity: { eid: 'b' } }])
174
+ * // [{ entity: { eid: 'b' } }, { entity: { eid: 'a' } }]
175
+ * ```
176
+ */
177
+ export let ordered = (ids: Eid[], held: Bundle[]): Bundle[] => {
178
+ let by = new Map(held.map((b) => [b.entity.eid, b]))
179
+ return ids.flatMap((id) => by.get(id) ?? [])
180
+ }
package/save.js ADDED
@@ -0,0 +1,93 @@
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
+ import { Refused } from "@yaks/graph/errors";
19
+ import { MEMORY } from "./comp.js";
20
+ /** The most context a memory carries, in lines. */ export let LINES = 2;
21
+ /** Why a save was rejected, worded so an agent can fix it. */ export let EMPTY = 'said: the words the person used, as they used them — a memory is their ' + 'sentence, never your summary of it';
22
+ /**
23
+ * The context, truncated: blank lines dropped, each line trimmed,
24
+ * {@link LINES} kept.
25
+ *
26
+ * ```ts
27
+ * clamped(' we were looking at\n\nthe recipe app\nand also this\nand this')
28
+ * // 'we were looking at\nthe recipe app'
29
+ * ```
30
+ */ export let clamped = (context)=>context.split('\n').map((l)=>l.trim()).filter(Boolean).slice(0, LINES).join('\n');
31
+ /** The component marking a memory as a correction somebody gave. */ export let FEEDBACK = 'feedback';
32
+ /**
33
+ * A mark on an entity that already holds the words, as the bundles
34
+ * that write it: `memory` and, for a correction, `feedback`, and nothing
35
+ * about the words themselves. Who marked it, and when, the graph stamps.
36
+ *
37
+ * ```ts
38
+ * marked({ eid: 'e1', context: 'looking at the recipe app' })
39
+ * // [{ entity: { eid: 'e1' },
40
+ * // memory: { context: 'looking at the recipe app' } }]
41
+ * ```
42
+ */ export let marked = (m)=>{
43
+ let context = clamped(m.context ?? '');
44
+ let about = (m.about ?? '').trim();
45
+ return [
46
+ {
47
+ entity: {
48
+ eid: m.eid
49
+ },
50
+ [MEMORY]: {
51
+ ...m.space ? {
52
+ space: m.space
53
+ } : {},
54
+ ...m.scope ? {
55
+ scope: m.scope
56
+ } : {},
57
+ ...context ? {
58
+ context
59
+ } : {},
60
+ ...about ? {
61
+ about
62
+ } : {}
63
+ },
64
+ ...m.feedback ? {
65
+ [FEEDBACK]: m.feedback === true ? {} : {
66
+ by: m.feedback
67
+ }
68
+ } : {}
69
+ }
70
+ ];
71
+ };
72
+ /**
73
+ * Words the graph holds nowhere yet, as the bundles that keep them:
74
+ * a doc whose body is the words exactly as they were said, marked. The byline
75
+ * is stamped by the graph, so nothing here writes one.
76
+ */ export let saved = (m)=>{
77
+ let said = m.said.trim();
78
+ if (!said) throw new Refused(EMPTY);
79
+ let title = (m.title ?? '').trim();
80
+ let [mark] = marked(m);
81
+ return [
82
+ {
83
+ ...mark,
84
+ doc: {
85
+ ...title ? {
86
+ title
87
+ } : {},
88
+ body: said
89
+ }
90
+ }
91
+ ];
92
+ };
93
+ //# sourceMappingURL=save.js.map
package/save.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"save.js","sources":["./save.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,4EAA4E;AAC5E,gFAAgF;AAChF,yEAAyE;AACzE,EAAE;AACF,yEAAyE;AACzE,kBAAkB;AAClB,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,UAAU;AACV,EAAE;AACF,iFAAiF;AACjF,uEAAuE;AACvE,4EAA4E;AAC5E,8EAA8E;AAC9E,gDAAgD;AAGhD,SAAS,OAAO,kCAAuC;AACvD,SAAS,MAAM,oBAAmB;AAElC,iDAAiD,GACjD,OAAO,IAAI,QAAQ,EAAC;AAEpB,4DAA4D,GAC5D,OAAO,IAAI,QACT,4EACA,qCAAoC;AAEtC;;;;;;;;CAQC,GACD,OAAO,IAAI,UAAU,CAAC,UACpB,QAAQ,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAM,EAAE,IAAI,IAAI,MAAM,CAAC,SAC7C,KAAK,CAAC,GAAG,OAAO,IAAI,CAAC,MAAK;AA6B/B,kEAAkE,GAClE,OAAO,IAAI,WAAW,WAAU;AAEhC;;;;;;;;;;CAUC,GACD,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,UAAU,QAAQ,EAAE,OAAO,IAAI;EACnC,IAAI,QAAQ,CAAC,EAAE,KAAK,IAAI,EAAE,EAAE,IAAI;EAChC,OAAO;IAAC;MACN,QAAQ;QAAE,KAAK,EAAE,GAAG;MAAC;MACrB,CAAC,OAAO,EAAE;QACR,GAAI,EAAE,KAA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