@batalabs/virlow-mcp-core 3.19.0 → 3.68.0

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 (61) hide show
  1. package/LICENSE +8 -18
  2. package/README.md +1 -1
  3. package/dist/api.d.ts +14 -0
  4. package/dist/api.d.ts.map +1 -1
  5. package/dist/api.js +6 -0
  6. package/dist/api.js.map +1 -1
  7. package/dist/attrs-extract.d.ts +48 -0
  8. package/dist/attrs-extract.d.ts.map +1 -0
  9. package/dist/attrs-extract.js +153 -0
  10. package/dist/attrs-extract.js.map +1 -0
  11. package/dist/attrs.d.ts +445 -0
  12. package/dist/attrs.d.ts.map +1 -0
  13. package/dist/attrs.js +604 -0
  14. package/dist/attrs.js.map +1 -0
  15. package/dist/cjs/api.d.ts +14 -0
  16. package/dist/cjs/api.js +6 -0
  17. package/dist/cjs/attrs-extract.d.ts +47 -0
  18. package/dist/cjs/attrs-extract.js +159 -0
  19. package/dist/cjs/attrs.d.ts +444 -0
  20. package/dist/cjs/attrs.js +635 -0
  21. package/dist/cjs/index.d.ts +4 -0
  22. package/dist/cjs/index.js +22 -1
  23. package/dist/cjs/memories.d.ts +79 -1
  24. package/dist/cjs/memories.js +249 -15
  25. package/dist/cjs/memory-graph.d.ts +105 -0
  26. package/dist/cjs/memory-graph.js +270 -0
  27. package/dist/cjs/memory-note.d.ts +57 -0
  28. package/dist/cjs/memory-note.js +174 -10
  29. package/dist/cjs/memory-secrets.d.ts +19 -0
  30. package/dist/cjs/memory-secrets.js +108 -0
  31. package/dist/cjs/notes.d.ts +208 -2
  32. package/dist/cjs/notes.js +721 -12
  33. package/dist/index.d.ts +4 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +2 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/memories.d.ts +79 -1
  38. package/dist/memories.d.ts.map +1 -1
  39. package/dist/memories.js +249 -15
  40. package/dist/memories.js.map +1 -1
  41. package/dist/memory-graph.d.ts +106 -0
  42. package/dist/memory-graph.d.ts.map +1 -0
  43. package/dist/memory-graph.js +258 -0
  44. package/dist/memory-graph.js.map +1 -0
  45. package/dist/memory-note.d.ts +57 -0
  46. package/dist/memory-note.d.ts.map +1 -1
  47. package/dist/memory-note.js +170 -10
  48. package/dist/memory-note.js.map +1 -1
  49. package/dist/memory-secrets.d.ts +20 -0
  50. package/dist/memory-secrets.d.ts.map +1 -0
  51. package/dist/memory-secrets.js +103 -0
  52. package/dist/memory-secrets.js.map +1 -0
  53. package/dist/notes.d.ts +208 -2
  54. package/dist/notes.d.ts.map +1 -1
  55. package/dist/notes.js +722 -13
  56. package/dist/notes.js.map +1 -1
  57. package/dist/tools.d.ts +2 -2
  58. package/dist/tools.d.ts.map +1 -1
  59. package/dist/tools.js +464 -9
  60. package/dist/tools.js.map +1 -1
  61. package/package.json +15 -5
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NEIGHBOUR_BOOST = exports.DIRECT_BOOST = exports.SINGLE_VALUED = exports.ONE_SUBJECT_PER_OBJECT = exports.ONE_OBJECT_PER_SUBJECT = void 0;
4
+ exports.entityKey = entityKey;
5
+ exports.normalizePredicate = normalizePredicate;
6
+ exports.heldAt = heldAt;
7
+ exports.memoryHeldAt = memoryHeldAt;
8
+ exports.buildGraph = buildGraph;
9
+ exports.entitiesMentioned = entitiesMentioned;
10
+ exports.neighbours = neighbours;
11
+ exports.rankMemories = rankMemories;
12
+ exports.supersededBy = supersededBy;
13
+ exports.graphHealth = graphHealth;
14
+ /** The matching key for a name: case, spacing and a leading article do not
15
+ * make a different entity. */
16
+ function entityKey(name) {
17
+ return name
18
+ .trim()
19
+ .toLowerCase()
20
+ .replace(/\s+/g, ' ')
21
+ .replace(/^the /, '');
22
+ }
23
+ /**
24
+ * Predicates where one side holds one value at a time, so a new fact ends
25
+ * the old one. Which side matters:
26
+ * - one object per subject: a person works at one place, reports to one
27
+ * manager (Dana works_at Acme, then Dana works_at Initech);
28
+ * - one subject per object: a project has one lead (Dana leads Atlas, then
29
+ * Sam leads Atlas).
30
+ * Anything else accumulates (prefers, uses, knows).
31
+ */
32
+ exports.ONE_OBJECT_PER_SUBJECT = new Set([
33
+ 'led_by',
34
+ 'owned_by',
35
+ 'managed_by',
36
+ 'reports_to',
37
+ 'works_at',
38
+ 'lives_in',
39
+ 'based_in',
40
+ 'located_in',
41
+ 'role',
42
+ 'status',
43
+ 'title',
44
+ ]);
45
+ exports.ONE_SUBJECT_PER_OBJECT = new Set(['leads', 'owns', 'manages']);
46
+ /** Either kind: a predicate that holds one value at a time. */
47
+ exports.SINGLE_VALUED = new Set([...exports.ONE_OBJECT_PER_SUBJECT, ...exports.ONE_SUBJECT_PER_OBJECT]);
48
+ /** snake_case, so "Works at" and "works_at" are one predicate. */
49
+ function normalizePredicate(p) {
50
+ return p
51
+ .trim()
52
+ .toLowerCase()
53
+ .replace(/[\s-]+/g, '_')
54
+ .replace(/[^a-z0-9_]/g, '');
55
+ }
56
+ /** A date or ISO timestamp as comparable milliseconds; bare dates are the
57
+ * start of that UTC day. */
58
+ function when(value) {
59
+ if (!value)
60
+ return null;
61
+ const t = Date.parse(value.length === 10 ? `${value}T00:00:00Z` : value);
62
+ return Number.isNaN(t) ? null : t;
63
+ }
64
+ /** Whether a span held at `at`: started on or before it, ended after it. */
65
+ function heldAt(from, to, at) {
66
+ const start = when(from);
67
+ const end = when(to);
68
+ if (start !== null && start > at)
69
+ return false;
70
+ if (end !== null && end <= at)
71
+ return false;
72
+ return true;
73
+ }
74
+ /**
75
+ * Whether a memory's fact held at `at`. It starts at `valid_from`, else the
76
+ * earliest date its relations give (a fact about "since January" learned
77
+ * today started in January), else when it was learned.
78
+ */
79
+ function memoryHeldAt(memory, at) {
80
+ const relationStarts = (memory.meta.relations ?? [])
81
+ .map((r) => r.from)
82
+ .filter((f) => !!f && when(f) !== null)
83
+ .sort((a, b) => when(a) - when(b));
84
+ const start = memory.meta.validFrom ?? relationStarts[0] ?? memory.meta.created;
85
+ return heldAt(start, memory.meta.validTo, at);
86
+ }
87
+ function buildGraph(memories) {
88
+ const entities = new Map();
89
+ const spellings = new Map();
90
+ const edges = [];
91
+ const touch = (name, memoryId) => {
92
+ const key = entityKey(name);
93
+ let entity = entities.get(key);
94
+ if (!entity) {
95
+ entity = { key, name: name.trim(), memoryIds: new Set(), edges: [] };
96
+ entities.set(key, entity);
97
+ spellings.set(key, new Map());
98
+ }
99
+ entity.memoryIds.add(memoryId);
100
+ const counts = spellings.get(key);
101
+ counts.set(name.trim(), (counts.get(name.trim()) ?? 0) + 1);
102
+ return entity;
103
+ };
104
+ for (const memory of memories) {
105
+ for (const name of memory.meta.about ?? [])
106
+ touch(name, memory.id);
107
+ for (const relation of memory.meta.relations ?? []) {
108
+ const edge = { ...relation, p: normalizePredicate(relation.p), memoryId: memory.id };
109
+ edges.push(edge);
110
+ touch(relation.s, memory.id).edges.push(edge);
111
+ // The object is an entity only if something else names it as one;
112
+ // "async standups" as the object of prefers stays a literal.
113
+ const objectKey = entityKey(relation.o);
114
+ if (entities.has(objectKey) || isEntityLike(relation.o)) {
115
+ touch(relation.o, memory.id).edges.push(edge);
116
+ }
117
+ }
118
+ }
119
+ for (const [key, counts] of spellings) {
120
+ const [best] = [...counts.entries()].sort((a, b) => b[1] - a[1]);
121
+ if (best)
122
+ entities.get(key).name = best[0];
123
+ }
124
+ return { entities, edges };
125
+ }
126
+ /** A capitalised name reads as an entity (Atlas, Dana Whitfield, Fly.io);
127
+ * a lower-case phrase reads as a value (async standups, dark mode). */
128
+ function isEntityLike(value) {
129
+ return /^[A-Z0-9]/.test(value.trim());
130
+ }
131
+ /** Entities named in a piece of text (a prompt, a query), longest names
132
+ * first so "Dana Whitfield" wins over "Dana". Whole words only. */
133
+ function entitiesMentioned(graph, text) {
134
+ // Dots survive only inside a name (Fly.io); a full stop after a word
135
+ // would otherwise hide the word.
136
+ const haystack = ` ${text
137
+ .toLowerCase()
138
+ .replace(/[^a-z0-9.\s]/g, ' ')
139
+ .replace(/\.(?![a-z0-9])|(?<![a-z0-9])\./g, ' ')
140
+ .replace(/\s+/g, ' ')} `;
141
+ const found = [];
142
+ const byLength = [...graph.entities.values()].sort((a, b) => b.key.length - a.key.length);
143
+ let remaining = haystack;
144
+ for (const entity of byLength) {
145
+ const needle = ` ${entity.key} `;
146
+ if (entity.key.length < 2 || !remaining.includes(needle))
147
+ continue;
148
+ found.push(entity);
149
+ remaining = remaining.split(needle).join(' ');
150
+ }
151
+ return found;
152
+ }
153
+ /** Entities one relation away from any of `from`. */
154
+ function neighbours(graph, from) {
155
+ const seen = new Set(from.map((e) => e.key));
156
+ const result = [];
157
+ for (const entity of from) {
158
+ for (const edge of entity.edges) {
159
+ for (const end of [edge.s, edge.o]) {
160
+ const key = entityKey(end);
161
+ const other = graph.entities.get(key);
162
+ if (other && !seen.has(key)) {
163
+ seen.add(key);
164
+ result.push(other);
165
+ }
166
+ }
167
+ }
168
+ }
169
+ return result;
170
+ }
171
+ /** How much the graph and recency move a similarity score. Small on
172
+ * purpose: similarity still decides, the graph breaks ties and pulls in
173
+ * facts that share an entity with the query but none of its words. */
174
+ exports.DIRECT_BOOST = 0.15;
175
+ exports.NEIGHBOUR_BOOST = 0.07;
176
+ const RECENCY_WEIGHT = 0.08;
177
+ const RECENCY_HORIZON_DAYS = 365;
178
+ function rankMemories(graph, query, scored, opts) {
179
+ const at = opts.at ?? Date.now();
180
+ const direct = entitiesMentioned(graph, query);
181
+ const near = neighbours(graph, direct);
182
+ const directIds = new Set(direct.flatMap((e) => [...e.memoryIds]));
183
+ const nearIds = new Set(near.flatMap((e) => [...e.memoryIds]));
184
+ return scored
185
+ .filter(({ memory }) => opts.includeHistory || memoryHeldAt(memory, at))
186
+ .map((item) => {
187
+ let score = item.similarity;
188
+ if (directIds.has(item.memory.id))
189
+ score += exports.DIRECT_BOOST;
190
+ else if (nearIds.has(item.memory.id))
191
+ score += exports.NEIGHBOUR_BOOST;
192
+ const updated = Date.parse(item.memory.updatedAt);
193
+ if (!Number.isNaN(updated)) {
194
+ const ageDays = Math.max(0, (at - updated) / 86_400_000);
195
+ score -= RECENCY_WEIGHT * Math.min(1, ageDays / RECENCY_HORIZON_DAYS);
196
+ }
197
+ return { ...item, score };
198
+ })
199
+ .sort((a, b) => b.score - a.score)
200
+ .slice(0, opts.limit);
201
+ }
202
+ /**
203
+ * Current edges a new relation replaces: same subject and single-valued
204
+ * predicate, a different object, still holding when the new one starts.
205
+ */
206
+ function supersededBy(graph, relation, at) {
207
+ const p = normalizePredicate(relation.p);
208
+ const s = entityKey(relation.s);
209
+ const o = entityKey(relation.o);
210
+ const bySubject = exports.ONE_OBJECT_PER_SUBJECT.has(p);
211
+ const byObject = exports.ONE_SUBJECT_PER_OBJECT.has(p);
212
+ if (!bySubject && !byObject)
213
+ return [];
214
+ return graph.edges.filter((edge) => {
215
+ if (edge.p !== p || !heldAt(edge.from, edge.to, at))
216
+ return false;
217
+ const es = entityKey(edge.s);
218
+ const eo = entityKey(edge.o);
219
+ if (es === s && eo === o)
220
+ return false;
221
+ return bySubject ? es === s : eo === o;
222
+ });
223
+ }
224
+ /**
225
+ * Housekeeping findings for a tidy pass: memories linked to nothing, names
226
+ * that look like one entity spelled two ways, and single-valued predicates
227
+ * holding two values at once.
228
+ */
229
+ function graphHealth(graph, memories, at = Date.now()) {
230
+ const unlinked = memories
231
+ .filter((m) => !(m.meta.about?.length || m.meta.relations?.length))
232
+ .map((m) => m.id);
233
+ const names = [...graph.entities.values()];
234
+ const possibleDuplicates = [];
235
+ for (let i = 0; i < names.length; i++) {
236
+ for (let j = i + 1; j < names.length; j++) {
237
+ const a = names[i].key;
238
+ const b = names[j].key;
239
+ const [short, long] = a.length <= b.length ? [a, b] : [b, a];
240
+ // "dana" and "dana whitfield": one name is the first word(s) of the other.
241
+ if (short.length >= 3 && long.startsWith(`${short} `)) {
242
+ possibleDuplicates.push([names[i].name, names[j].name]);
243
+ }
244
+ }
245
+ }
246
+ const contradictions = [];
247
+ // Keyed on the side that must be unique: the subject for works_at, the
248
+ // object for leads. `values` are the other side.
249
+ const current = new Map();
250
+ for (const edge of graph.edges) {
251
+ if (!exports.SINGLE_VALUED.has(edge.p) || !heldAt(edge.from, edge.to, at))
252
+ continue;
253
+ const bySubject = exports.ONE_OBJECT_PER_SUBJECT.has(edge.p);
254
+ const anchor = bySubject ? edge.s : edge.o;
255
+ const key = `${entityKey(anchor)}|${edge.p}`;
256
+ if (!current.has(key))
257
+ current.set(key, { anchor, predicate: edge.p, values: new Set() });
258
+ current.get(key).values.add(bySubject ? edge.o : edge.s);
259
+ }
260
+ for (const [key, { anchor, predicate, values }] of current) {
261
+ if (values.size < 2)
262
+ continue;
263
+ contradictions.push({
264
+ subject: graph.entities.get(key.split('|')[0])?.name ?? anchor,
265
+ predicate,
266
+ objects: [...values],
267
+ });
268
+ }
269
+ return { unlinked, possibleDuplicates, contradictions };
270
+ }
@@ -14,10 +14,51 @@ export interface MemoryMeta {
14
14
  confidence?: string;
15
15
  /** ISO timestamp of the first write; never overwritten by later updates. */
16
16
  created?: string;
17
+ /**
18
+ * `html` when the fact was written in the app's rich editor, so the body
19
+ * after the frontmatter is TipTap HTML rather than plain text. Absent
20
+ * means plain text, which is what the connector always writes: AI tools
21
+ * read and write text, and the app renders it as paragraphs.
22
+ */
23
+ format?: 'html';
24
+ /**
25
+ * The graph: the entities this fact is about (people, projects, places,
26
+ * tools), by name. Names are matched case-insensitively across memories,
27
+ * so every memory that says "Atlas" is about the same Atlas.
28
+ */
29
+ about?: string[];
30
+ /** Typed links the fact asserts, e.g. Sam leads Atlas. A relation lives on
31
+ * the memory that asserted it, so every edge has a source to open, check
32
+ * or delete. */
33
+ relations?: MemoryRelation[];
34
+ /** When the fact became true (YYYY-MM-DD or ISO). Absent: when it was
35
+ * learned (`created`). */
36
+ validFrom?: string;
37
+ /** When the fact stopped being true. Facts are ended, never deleted, when
38
+ * they are superseded, so history stays answerable. */
39
+ validTo?: string;
40
+ /** The memory that replaced this one, when one did. */
41
+ supersededBy?: string;
42
+ }
43
+ /**
44
+ * One edge: subject, predicate, object. `p` is a short verb phrase in
45
+ * snake_case ("leads", "works_at", "prefers"); `o` is an entity name or a
46
+ * literal ("async standups"). `from` and `to` bound when it held.
47
+ */
48
+ export interface MemoryRelation {
49
+ s: string;
50
+ p: string;
51
+ o: string;
52
+ from?: string;
53
+ to?: string;
17
54
  }
18
55
  export interface ParsedMemoryNote {
56
+ /** The fact as plain text: what AI tools read, what gets embedded. For an
57
+ * HTML body, its text with line breaks and list markers kept. */
19
58
  fact: string;
20
59
  meta: MemoryMeta;
60
+ /** The body as written, when `meta.format` is `html`. */
61
+ html?: string;
21
62
  }
22
63
  /**
23
64
  * The note type a memory is written as.
@@ -36,6 +77,20 @@ export declare const MEMORY_NOTE_TYPE = "memory";
36
77
  * (or a test) can build a legacy body and confirm it still reads.
37
78
  */
38
79
  export declare function toCodeEnvelope(body: string): string;
80
+ /**
81
+ * A rich fact as text an AI can read: one line per paragraph, heading or
82
+ * list item, list items marked, code and inline marks reduced to their text.
83
+ * Entities are decoded, so a fact that talks about `<p>` tags reads back as
84
+ * exactly that.
85
+ */
86
+ export declare function memoryHtmlToText(html: string): string;
87
+ /**
88
+ * Plain text as the rich editor's HTML: a paragraph per blank-line-separated
89
+ * block, single line breaks kept, everything escaped. Used to open a
90
+ * connector-written (plain) memory in the editor.
91
+ */
92
+ export declare function memoryTextToHtml(text: string): string;
93
+ export declare function looksLikeHtml(fact: string): boolean;
39
94
  /**
40
95
  * Split a decrypted note body into its fact and metadata.
41
96
  *
@@ -50,6 +105,8 @@ export declare function parseMemoryNote(decryptedContent: string): ParsedMemoryN
50
105
  * there is no metadata to record.
51
106
  */
52
107
  export declare function serializeMemoryBody(fact: string, meta: MemoryMeta): string;
108
+ /** The app's rich editor output, marked as HTML. */
109
+ export declare function serializeMemoryHtml(html: string, meta: MemoryMeta): string;
53
110
  /**
54
111
  * Metadata for an update: named keys win, unnamed keys carry forward, and
55
112
  * `created` is pinned to the first write so an in-place dedupe merge cannot
@@ -2,12 +2,65 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MEMORY_NOTE_TYPE = void 0;
4
4
  exports.toCodeEnvelope = toCodeEnvelope;
5
+ exports.memoryHtmlToText = memoryHtmlToText;
6
+ exports.memoryTextToHtml = memoryTextToHtml;
7
+ exports.looksLikeHtml = looksLikeHtml;
5
8
  exports.parseMemoryNote = parseMemoryNote;
6
9
  exports.serializeMemoryBody = serializeMemoryBody;
10
+ exports.serializeMemoryHtml = serializeMemoryHtml;
7
11
  exports.mergeMeta = mergeMeta;
8
12
  const yaml_1 = require("yaml");
13
+ const attrs_extract_js_1 = require("./attrs-extract.js");
9
14
  /** Serialisation order, so a rewrite of unchanged metadata is a no-op diff. */
10
- const KEY_ORDER = ['source', 'tags', 'confidence', 'created'];
15
+ const KEY_ORDER = [
16
+ 'source',
17
+ 'tags',
18
+ 'confidence',
19
+ 'created',
20
+ 'format',
21
+ 'about',
22
+ 'relations',
23
+ 'validFrom',
24
+ 'validTo',
25
+ 'supersededBy',
26
+ ];
27
+ /** The frontmatter key for each field: snake_case on disk, as a person
28
+ * editing the YAML would write it. */
29
+ const YAML_KEY = {
30
+ validFrom: 'valid_from',
31
+ validTo: 'valid_to',
32
+ supersededBy: 'superseded_by',
33
+ };
34
+ /** A date field as a string: YAML reads an unquoted date as a Date. */
35
+ function dateField(value) {
36
+ if (typeof value === 'string' && value.trim() !== '')
37
+ return value.trim();
38
+ if (value instanceof Date && !Number.isNaN(value.getTime())) {
39
+ const iso = value.toISOString();
40
+ // A bare date comes back as midnight UTC; keep it a date.
41
+ return iso.endsWith('T00:00:00.000Z') ? iso.slice(0, 10) : iso;
42
+ }
43
+ return undefined;
44
+ }
45
+ function coerceRelation(raw) {
46
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
47
+ return null;
48
+ const r = raw;
49
+ const text = (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : null);
50
+ const s = text(r.s);
51
+ const p = text(r.p);
52
+ const o = text(r.o);
53
+ if (!s || !p || !o)
54
+ return null;
55
+ const relation = { s, p, o };
56
+ const from = dateField(r.from);
57
+ const to = dateField(r.to);
58
+ if (from)
59
+ relation.from = from;
60
+ if (to)
61
+ relation.to = to;
62
+ return relation;
63
+ }
11
64
  const FENCE = '---';
12
65
  /**
13
66
  * The note type a memory is written as.
@@ -66,8 +119,86 @@ function coerceMeta(raw) {
66
119
  // YAML parses unquoted ISO timestamps into Dates.
67
120
  meta.created = raw.created.toISOString();
68
121
  }
122
+ if (raw.format === 'html')
123
+ meta.format = 'html';
124
+ if (Array.isArray(raw.about)) {
125
+ const about = raw.about.filter((a) => typeof a === 'string' && a.trim() !== '');
126
+ if (about.length > 0)
127
+ meta.about = about.map((a) => a.trim());
128
+ }
129
+ if (Array.isArray(raw.relations)) {
130
+ // One malformed relation is dropped; its neighbours survive.
131
+ const relations = raw.relations
132
+ .map(coerceRelation)
133
+ .filter((r) => r !== null);
134
+ if (relations.length > 0)
135
+ meta.relations = relations;
136
+ }
137
+ const validFrom = dateField(raw.valid_from);
138
+ if (validFrom)
139
+ meta.validFrom = validFrom;
140
+ const validTo = dateField(raw.valid_to);
141
+ if (validTo)
142
+ meta.validTo = validTo;
143
+ if (typeof raw.superseded_by === 'string' && raw.superseded_by !== '') {
144
+ meta.supersededBy = raw.superseded_by;
145
+ }
69
146
  return meta;
70
147
  }
148
+ /**
149
+ * A rich fact as text an AI can read: one line per paragraph, heading or
150
+ * list item, list items marked, code and inline marks reduced to their text.
151
+ * Entities are decoded, so a fact that talks about `<p>` tags reads back as
152
+ * exactly that.
153
+ */
154
+ function memoryHtmlToText(html) {
155
+ const text = html
156
+ .replace(/<br\s*\/?>/gi, '\n')
157
+ // A list item's paragraph is the item, not a paragraph of its own.
158
+ .replace(/<li[^>]*>\s*(<p[^>]*>)?/gi, '- ')
159
+ .replace(/(<\/p>)?\s*<\/li>/gi, '\n')
160
+ .replace(/<\/(p|h[1-6]|blockquote|pre|ul|ol|table)>/gi, '\n\n')
161
+ .replace(/<\/tr>/gi, '\n')
162
+ .replace(/<\/(td|th)>/gi, ' ')
163
+ .replace(/<[^>]+>/g, '');
164
+ return (0, attrs_extract_js_1.decodeEntities)(text)
165
+ .split('\n')
166
+ .map((line) => line.replace(/[ \t]+$/, ''))
167
+ .join('\n')
168
+ .replace(/\n{3,}/g, '\n\n')
169
+ .trim();
170
+ }
171
+ /**
172
+ * Plain text as the rich editor's HTML: a paragraph per blank-line-separated
173
+ * block, single line breaks kept, everything escaped. Used to open a
174
+ * connector-written (plain) memory in the editor.
175
+ */
176
+ function memoryTextToHtml(text) {
177
+ const escape = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
178
+ const blocks = text.split(/\n{2,}/).filter((b) => b.trim() !== '');
179
+ if (blocks.length === 0)
180
+ return '<p></p>';
181
+ return blocks.map((b) => `<p>${b.split('\n').map(escape).join('<br>')}</p>`).join('');
182
+ }
183
+ /**
184
+ * A plain-text fact that is really HTML: it opens and closes with a block
185
+ * tag. AI tools told that Virlow notes are HTML sometimes write a memory the
186
+ * same way, without the `format` marker the app adds, and it then showed its
187
+ * tags as text. A fact that merely mentions a tag ("every paragraph in
188
+ * <p>") does not start and end with one, so it stays text.
189
+ */
190
+ const BLOCK = '(p|ul|ol|h[1-6]|blockquote|pre|table|div)';
191
+ const OPENS_WITH_BLOCK = new RegExp(`^\\s*<${BLOCK}[\\s>]`, 'i');
192
+ const CLOSES_WITH_BLOCK = new RegExp(`</${BLOCK}>\\s*$`, 'i');
193
+ function looksLikeHtml(fact) {
194
+ return OPENS_WITH_BLOCK.test(fact) && CLOSES_WITH_BLOCK.test(fact);
195
+ }
196
+ function plainOrHtml(fact, meta) {
197
+ if (meta.format === 'html' || looksLikeHtml(fact)) {
198
+ return { fact: memoryHtmlToText(fact), meta, html: fact };
199
+ }
200
+ return { fact, meta };
201
+ }
71
202
  /**
72
203
  * Split a decrypted note body into its fact and metadata.
73
204
  *
@@ -82,19 +213,19 @@ function parseMemoryNote(decryptedContent) {
82
213
  // a plain note dropped into the folder by hand — still reads correctly.
83
214
  const body = unwrapEnvelope(decryptedContent);
84
215
  if (!body.startsWith(`${FENCE}\n`))
85
- return { fact: body, meta: {} };
216
+ return plainOrHtml(body, {});
86
217
  // Only the first fence pair is frontmatter; --- lines inside the fact are
87
218
  // ordinary content.
88
219
  const close = body.indexOf(`\n${FENCE}\n`, FENCE.length);
89
220
  if (close === -1)
90
- return { fact: body, meta: {} };
221
+ return plainOrHtml(body, {});
91
222
  const front = body.slice(FENCE.length + 1, close);
92
223
  const fact = body.slice(close + FENCE.length + 2);
93
224
  // An empty fence is the marker `serializeMemoryBody` writes when a fact
94
225
  // would otherwise be misread as its own frontmatter. Strip it and keep the
95
226
  // fact whole.
96
227
  if (front.trim() === '')
97
- return { fact, meta: {} };
228
+ return plainOrHtml(fact, {});
98
229
  let raw;
99
230
  try {
100
231
  raw = (0, yaml_1.parse)(front);
@@ -105,7 +236,7 @@ function parseMemoryNote(decryptedContent) {
105
236
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
106
237
  return { fact: body, meta: {} };
107
238
  }
108
- return { fact, meta: coerceMeta(raw) };
239
+ return plainOrHtml(fact, coerceMeta(raw));
109
240
  }
110
241
  function yamlScalar(value) {
111
242
  // Quote anything YAML would otherwise reinterpret (or that would break the
@@ -119,19 +250,42 @@ function yamlScalar(value) {
119
250
  * there is no metadata to record.
120
251
  */
121
252
  function serializeMemoryBody(fact, meta) {
253
+ // Plain text, always: `format` describes the body, so it is dropped here
254
+ // rather than carried forward from the memory being updated. An AI
255
+ // rewriting a rich memory writes text, and the marker must not survive
256
+ // onto a body it no longer describes.
257
+ const { format: _format, ...plain } = meta;
258
+ return writeBody(fact, plain);
259
+ }
260
+ /** The app's rich editor output, marked as HTML. */
261
+ function serializeMemoryHtml(html, meta) {
262
+ return writeBody(html, { ...meta, format: 'html' });
263
+ }
264
+ function writeBody(fact, meta) {
122
265
  const lines = [];
123
266
  for (const key of KEY_ORDER) {
124
267
  const value = meta[key];
125
268
  if (value === undefined)
126
269
  continue;
127
- if (key === 'tags') {
128
- const tags = value;
129
- if (tags.length === 0)
270
+ const name = YAML_KEY[key] ?? key;
271
+ if (key === 'tags' || key === 'about') {
272
+ const list = value;
273
+ if (list.length === 0)
274
+ continue;
275
+ lines.push(`${name}: [${list.map(yamlScalar).join(', ')}]`);
276
+ }
277
+ else if (key === 'relations') {
278
+ const relations = value;
279
+ if (relations.length === 0)
130
280
  continue;
131
- lines.push(`tags: [${tags.map(yamlScalar).join(', ')}]`);
281
+ // Flow style, one relation per line: JSON is valid YAML, and this
282
+ // keeps each edge readable and editable by hand.
283
+ lines.push(`${name}:`);
284
+ for (const r of relations)
285
+ lines.push(` - ${JSON.stringify(r)}`);
132
286
  }
133
287
  else {
134
- lines.push(`${key}: ${yamlScalar(value)}`);
288
+ lines.push(`${name}: ${yamlScalar(value)}`);
135
289
  }
136
290
  }
137
291
  if (lines.length === 0) {
@@ -155,6 +309,16 @@ function mergeMeta(existing, changes) {
155
309
  merged.tags = [...changes.tags];
156
310
  if (changes.confidence !== undefined)
157
311
  merged.confidence = changes.confidence;
312
+ if (changes.about !== undefined)
313
+ merged.about = [...changes.about];
314
+ if (changes.relations !== undefined)
315
+ merged.relations = changes.relations.map((r) => ({ ...r }));
316
+ if (changes.validFrom !== undefined)
317
+ merged.validFrom = changes.validFrom;
318
+ if (changes.validTo !== undefined)
319
+ merged.validTo = changes.validTo;
320
+ if (changes.supersededBy !== undefined)
321
+ merged.supersededBy = changes.supersededBy;
158
322
  // Pinned to the first write, so an in-place dedupe merge cannot make an old
159
323
  // memory look newly created.
160
324
  if (changes.created !== undefined && existing.created === undefined) {
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Refuses memories that contain credentials, before anything is written.
3
+ *
4
+ * Memories are captured automatically, so the rule cannot depend on the AI
5
+ * remembering not to save a key: a memory is encrypted, but it is recalled
6
+ * into prompts and shown in the app, and a secret has no business in either.
7
+ * The check is on-device and returns a reason, so the AI can say what it
8
+ * left out instead of retrying with the secret reworded.
9
+ *
10
+ * Deliberately narrow: patterns that are credentials with near certainty,
11
+ * plus long high-entropy tokens. A false positive costs one memory; a false
12
+ * negative puts a live key into every future prompt that recalls it.
13
+ */
14
+ /** What secret the text holds, or null when it holds none. */
15
+ export declare function findSecret(text: string): string | null;
16
+ export declare class SecretInMemoryError extends Error {
17
+ constructor(what: string);
18
+ }
19
+ export declare function assertNoSecret(...texts: string[]): void;