renor-engine 1.0.0 → 1.2.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 (110) hide show
  1. package/LICENSE +202 -661
  2. package/NOTICE +8 -6
  3. package/README.md +13 -8
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/api/server.js +10 -8
  6. package/dist/buildIdentity.js +18 -1
  7. package/dist/callPhases.js +82 -0
  8. package/dist/cli.js +36 -1
  9. package/dist/context/rowStore.js +1 -1
  10. package/dist/conversation/parser.js +40 -36
  11. package/dist/db/client.js +6 -4
  12. package/dist/db/handoffTable.js +31 -0
  13. package/dist/db/indexSalvage.js +24 -4
  14. package/dist/db/migrations.js +30 -2
  15. package/dist/db/sqlite.js +396 -0
  16. package/dist/digests/digestCache.js +6 -2
  17. package/dist/digests/digests.js +3 -3
  18. package/dist/digests/worker.js +3 -1
  19. package/dist/embeddings/caching.js +5 -5
  20. package/dist/embeddings/local.js +5 -3
  21. package/dist/embeddings/openai.js +4 -3
  22. package/dist/embeddings/simdScan.js +3 -1
  23. package/dist/embeddings/vectorIndex.js +0 -1
  24. package/dist/embeddings/vertex.js +123 -13
  25. package/dist/eval/cacheReport.js +7 -0
  26. package/dist/eval/context700-candidate.js +5 -5
  27. package/dist/eval/evalCache.js +46 -3
  28. package/dist/eval/indexSnapshots.js +549 -0
  29. package/dist/eval/pageDump.js +67 -0
  30. package/dist/eval/runManifest.js +6 -0
  31. package/dist/eval/textTokens.js +17 -0
  32. package/dist/evidence/attach.js +0 -3
  33. package/dist/evidence/evidenceCache.js +3 -3
  34. package/dist/evidence/ollamaChat.js +1 -1
  35. package/dist/evidence/options.js +46 -25
  36. package/dist/evidence/secondPass.js +8 -170
  37. package/dist/extraction/factExtractor.js +1 -1
  38. package/dist/extraction/jevDecisionModel.js +307 -0
  39. package/dist/extraction/preferenceExtractor.js +1 -4
  40. package/dist/extraction/secretGuard.js +7 -3
  41. package/dist/extraction/typedFacts.js +1 -1
  42. package/dist/importing/apply.js +42 -14
  43. package/dist/importing/cli.js +9 -8
  44. package/dist/importing/existing.js +2 -0
  45. package/dist/importing/facts.js +0 -2
  46. package/dist/importing/plan.js +0 -5
  47. package/dist/importing/source.js +1 -1
  48. package/dist/indexer/parser.js +4 -1
  49. package/dist/indexer/pipeline.js +99 -279
  50. package/dist/indexer/walker.js +11 -25
  51. package/dist/learning/cli.js +113 -0
  52. package/dist/learning/schema.js +144 -0
  53. package/dist/learning/settings.js +45 -0
  54. package/dist/learning/store.js +267 -0
  55. package/dist/learning/tap.js +401 -0
  56. package/dist/mcp/server.js +36 -6
  57. package/dist/memory/dreamer/adjudicate.js +215 -0
  58. package/dist/memory/dreamer/apply.js +120 -0
  59. package/dist/memory/dreamer/budget.js +64 -0
  60. package/dist/memory/dreamer/candidates.js +149 -0
  61. package/dist/memory/dreamer/collection.js +104 -0
  62. package/dist/memory/dreamer/dreamer.js +352 -0
  63. package/dist/memory/dreamer/review.js +111 -0
  64. package/dist/memory/factConflicts.js +2 -0
  65. package/dist/memory/handoff.js +363 -0
  66. package/dist/memory/lifecycle.js +338 -80
  67. package/dist/memory/sourceName.js +77 -1
  68. package/dist/memory/statusFacts.js +61 -0
  69. package/dist/memory/writer.js +3 -2
  70. package/dist/memorymap/memoryMap.js +39 -13
  71. package/dist/memorymap/replacements.js +8 -3
  72. package/dist/mvp/agentMemory.js +109 -50
  73. package/dist/mvp/answerCheck.js +211 -0
  74. package/dist/mvp/cli.js +14 -1
  75. package/dist/mvp/compileCache.js +3 -10
  76. package/dist/mvp/compileSeed.js +9 -3
  77. package/dist/mvp/config.js +4 -0
  78. package/dist/mvp/contextDistinct.js +53 -0
  79. package/dist/mvp/contextProfile.js +87 -0
  80. package/dist/mvp/directorySurface.js +68 -0
  81. package/dist/mvp/engine.js +39 -26
  82. package/dist/mvp/exportAll.js +36 -2
  83. package/dist/mvp/factMarkers.js +18 -2
  84. package/dist/mvp/history.js +5 -4
  85. package/dist/mvp/log.js +118 -0
  86. package/dist/mvp/server.js +759 -136
  87. package/dist/mvp/serverCard.js +12 -3
  88. package/dist/mvp/telemetry.js +35 -2
  89. package/dist/net/poolFetch.js +174 -0
  90. package/dist/recall/actionRecall.js +282 -0
  91. package/dist/recall/autoRecall.js +447 -0
  92. package/dist/recall/searchRecall.js +189 -0
  93. package/dist/retrieval/entityLookup.js +53 -4
  94. package/dist/retrieval/orchestrator.js +148 -10
  95. package/dist/retrieval/plainWording.js +236 -0
  96. package/dist/retrieval/rankingTrace.js +184 -0
  97. package/dist/retrieval/readerLayout.js +143 -224
  98. package/dist/router/routerCache.js +2 -2
  99. package/dist/sharing/cli.js +181 -0
  100. package/dist/sharing/examples.js +136 -0
  101. package/dist/sharing/fields.js +225 -0
  102. package/dist/sharing/loop.js +80 -0
  103. package/dist/sharing/project.js +327 -0
  104. package/dist/sharing/send.js +466 -0
  105. package/dist/sharing/state.js +222 -0
  106. package/dist/sharing/wording.js +48 -0
  107. package/dist/watcher/watcher.js +5 -3
  108. package/package.json +5 -7
  109. package/dist/BUILD.json +0 -6
  110. package/dist/importing/index.js +0 -29
@@ -0,0 +1,401 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.learningObserver = learningObserver;
7
+ const buildIdentity_1 = require("../buildIdentity");
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const agentMemory_1 = require("../mvp/agentMemory");
10
+ const scope_1 = require("../mvp/scope");
11
+ const rankingTrace_1 = require("../retrieval/rankingTrace");
12
+ const schema_1 = require("./schema");
13
+ const store_1 = require("./store");
14
+ const RETRIEVAL_MODES = ['facts', 'hybrid', 'semantic', 'keyword'];
15
+ // A lane string: lane names joined by '+' (semantic+content+recency). Closed vocabulary from the product's own labels.
16
+ const REASON = /^[a-z][a-z0-9+-]{0,127}$/;
17
+ const MODEL = /^[A-Za-z0-9._:/+-]{1,120}$/;
18
+ const COMMIT = /^[0-9a-f]{7,40}$/;
19
+ const MAX_CITES = 20;
20
+ const norm = (value) => value.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim();
21
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
22
+ const recordsOf = (value) => (Array.isArray(value) ? value.filter(isRecord) : []);
23
+ let build;
24
+ /** The commit of the running build, read once; null when the build is unstamped. */
25
+ function buildCommit() {
26
+ if (build === undefined) {
27
+ const commit = (0, buildIdentity_1.readBuildIdentity)().commit;
28
+ build = COMMIT.test(commit) ? commit : null;
29
+ }
30
+ return build;
31
+ }
32
+ /** The reply as the tool built it: its JSON body and the text it was sent as (the text is what the token budget counted). */
33
+ function replyOf(result) {
34
+ if (!isRecord(result))
35
+ return null;
36
+ const first = Array.isArray(result.content) ? result.content[0] : undefined;
37
+ const text = isRecord(first) && typeof first.text === 'string' ? first.text : null;
38
+ if (text !== null) {
39
+ try {
40
+ const parsed = JSON.parse(text);
41
+ return isRecord(parsed) ? { body: parsed, text } : null;
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ if (isRecord(result.structuredContent)) {
48
+ return { body: result.structuredContent, text: JSON.stringify(result.structuredContent) };
49
+ }
50
+ return null;
51
+ }
52
+ /** The identity of a memory named by its id: `note:<path>`, `entry:<path>#<hash>` (its note) or `fact:<eventId>` (one fact's event). */
53
+ function identityOf(log, id) {
54
+ if (id.startsWith('note:'))
55
+ return { kind: 'note', memoryKey: log.key('note', id.slice(5)) };
56
+ if (id.startsWith('entry:')) {
57
+ const hashAt = id.lastIndexOf('#');
58
+ const notePath = hashAt > 6 ? id.slice(6, hashAt) : id.slice(6);
59
+ return { kind: 'note', memoryKey: log.key('note', notePath) };
60
+ }
61
+ if (id.startsWith('fact:'))
62
+ return { kind: 'event', memoryKey: log.key('event', id.slice(5)) };
63
+ return { kind: 'unkeyed', memoryKey: null };
64
+ }
65
+ /**
66
+ * A cite is a memory id (note:, entry: or fact:), a note's path, or a fact's subject: the save tools' own wording, and the same
67
+ * three forms readUsefulness.ts matches. A bare string with a path's shape is a note; any other bare string is a subject, and a
68
+ * subject is keyed within the scope of the save that names it, as a fact's subject is.
69
+ */
70
+ function citeOf(log, cite, scope) {
71
+ const value = cite.trim();
72
+ if (value === '')
73
+ return { target: 'unkeyed', memoryKey: null, subjectKey: null };
74
+ if (value.startsWith('note:') || value.startsWith('entry:')) {
75
+ return { target: 'note', memoryKey: identityOf(log, value).memoryKey, subjectKey: null };
76
+ }
77
+ if (value.startsWith('fact:'))
78
+ return { target: 'event', memoryKey: identityOf(log, value).memoryKey, subjectKey: null };
79
+ if (/\.md$/i.test(value) || value.includes('/'))
80
+ return { target: 'note', memoryKey: log.key('note', value), subjectKey: null };
81
+ return { target: 'subject', memoryKey: null, subjectKey: log.key('subject', scope, norm(value)) };
82
+ }
83
+ /** A candidate with no ranker trace: the columns the ranker adds are null, and so are its positions and the budget's decision. */
84
+ const UNTRACED = { rank: null, base: null, terms: null, poolRank: null, windowPos: null, budgetKept: null };
85
+ /** A fact as a retrieval served it: the memory is the scope, subject and predicate; the subject alone joins a cite that names it. */
86
+ function factCandidate(log, subject, fact) {
87
+ const predicate = typeof fact.predicate === 'string' ? fact.predicate : null;
88
+ const scope = (0, scope_1.normalizeScope)(typeof fact.scope === 'string' ? fact.scope : 'global');
89
+ const current = typeof fact.current === 'boolean' ? fact.current : null;
90
+ if (typeof subject !== 'string' || predicate === null)
91
+ return unkeyed(null, null, current);
92
+ return {
93
+ ...UNTRACED,
94
+ kind: 'fact',
95
+ memoryKey: log.key('fact', scope, norm(subject), norm(predicate)),
96
+ subjectKey: log.key('subject', scope, norm(subject)),
97
+ sectionKey: null,
98
+ score: null,
99
+ reason: 'fact',
100
+ matched: null,
101
+ current,
102
+ text: typeof fact.object === 'string' ? `${subject} ${predicate}: ${fact.object}` : null,
103
+ };
104
+ }
105
+ /** A note hit: its path is the memory, its heading path (when there is one) the section within it. */
106
+ function noteCandidate(log, hit) {
107
+ const notePath = typeof hit.notePath === 'string' && hit.notePath !== '' ? hit.notePath : null;
108
+ const headingPath = typeof hit.headingPath === 'string' && hit.headingPath !== '' ? hit.headingPath : null;
109
+ const score = typeof hit.score === 'number' && Number.isFinite(hit.score) ? hit.score : null;
110
+ const reason = typeof hit.reason === 'string' && REASON.test(hit.reason) ? hit.reason : null;
111
+ const matched = hit.matched === false ? false : null;
112
+ if (notePath === null)
113
+ return unkeyed(score, reason, null, matched);
114
+ return {
115
+ ...UNTRACED,
116
+ kind: 'note',
117
+ memoryKey: log.key('note', notePath),
118
+ subjectKey: null,
119
+ sectionKey: headingPath === null ? null : log.key('section', notePath, headingPath),
120
+ score,
121
+ reason,
122
+ matched,
123
+ current: null,
124
+ text: typeof hit.text === 'string' ? hit.text : null,
125
+ };
126
+ }
127
+ function unkeyed(score, reason, current, matched = null) {
128
+ return { ...UNTRACED, kind: 'unkeyed', memoryKey: null, subjectKey: null, sectionKey: null, score, reason, matched, current };
129
+ }
130
+ /** The candidates a reply served, in the order it served them. Facts come first, as the reply lists them. */
131
+ function servedOf(log, tool, body) {
132
+ if (tool === 'retrieve_memory') {
133
+ return recordsOf(body.facts).map(fact => ({ record: factCandidate(log, body.subject, fact), traceKey: null, notePath: null, headingPath: null }));
134
+ }
135
+ const notes = (items) => items.map(item => ({
136
+ record: noteCandidate(log, item),
137
+ notePath: typeof item.notePath === 'string' ? item.notePath : null,
138
+ headingPath: typeof item.headingPath === 'string' ? item.headingPath : null,
139
+ traceKey: typeof item.notePath === 'string' && item.notePath !== '' && typeof item.text === 'string'
140
+ ? (0, rankingTrace_1.traceKey)(item.notePath, typeof item.headingPath === 'string' ? item.headingPath : undefined, item.text)
141
+ : null,
142
+ }));
143
+ if (tool === 'get_context') {
144
+ return [
145
+ ...recordsOf(body.facts).map(fact => ({ record: factCandidate(log, fact.subject, fact), traceKey: null, notePath: null, headingPath: null })),
146
+ ...notes(recordsOf(body.memories)),
147
+ ];
148
+ }
149
+ return notes(recordsOf(body.hits));
150
+ }
151
+ /** The ranker's record of a candidate, as the candidate row carries it. */
152
+ function tracedFields(entry) {
153
+ return { base: entry.base, terms: entry.terms, poolRank: entry.poolRank, windowPos: entry.windowPos, budgetKept: entry.budgetKept };
154
+ }
155
+ /**
156
+ * The rows of one retrieval: each served candidate at its rank, then every candidate the ranker scored or presented that the reply
157
+ * did not serve (rank null). A fact-lane hit (reason `fact`) is left out of the second group: a fact is recorded from its own row.
158
+ */
159
+ function candidateRows(log, served, trace) {
160
+ const rows = [];
161
+ const servedKeys = new Set();
162
+ let servedNoteIndex = 0;
163
+ served.forEach((item, index) => {
164
+ if (item.traceKey !== null)
165
+ servedKeys.add(item.traceKey);
166
+ let entry = trace && item.traceKey !== null
167
+ ? trace.byKey(item.traceKey) ?? (item.notePath === null ? undefined : trace.byLocation(item.notePath, item.headingPath))
168
+ : undefined;
169
+ if (!entry && trace && item.record.memoryKey !== null) {
170
+ const sameNote = trace.all().filter(candidate => candidate.notePath !== ''
171
+ && log.key('note', candidate.notePath) === item.record.memoryKey);
172
+ if (sameNote.length === 1)
173
+ [entry] = sameNote;
174
+ }
175
+ if (!entry && trace && item.notePath !== null) {
176
+ const shownFile = node_path_1.default.basename(item.notePath);
177
+ const sameFile = trace.all().filter(candidate => node_path_1.default.basename(candidate.notePath) === shownFile);
178
+ if (sameFile.length === 1)
179
+ [entry] = sameFile;
180
+ }
181
+ if (entry?.budgetKept === null && trace?.all().some(candidate => candidate.budgetKept !== null))
182
+ entry = undefined;
183
+ if (!entry && trace && item.notePath !== null) {
184
+ const hasBudget = trace.all().some(candidate => candidate.budgetKept !== null);
185
+ entry = trace.all()
186
+ .filter(candidate => hasBudget ? candidate.budgetKept === true : candidate.windowPos !== null)
187
+ .sort((a, b) => a.windowPos - b.windowPos)[servedNoteIndex];
188
+ }
189
+ if (item.notePath !== null)
190
+ servedNoteIndex++;
191
+ if (entry)
192
+ servedKeys.add(entry.key);
193
+ rows.push({ ...item.record, rank: index + 1, ...(entry ? tracedFields(entry) : {}) });
194
+ });
195
+ if (trace) {
196
+ for (const entry of trace.all()) {
197
+ if (servedKeys.has(entry.key) || entry.reason === 'fact')
198
+ continue;
199
+ const score = entry.base + entry.terms.reduce((sum, term) => sum + term, 0);
200
+ rows.push({
201
+ ...tracedFields(entry),
202
+ rank: null,
203
+ kind: entry.notePath === '' ? 'unkeyed' : 'note',
204
+ memoryKey: entry.notePath === '' ? null : log.key('note', entry.notePath),
205
+ subjectKey: null,
206
+ sectionKey: entry.notePath !== '' && entry.headingPath !== null ? log.key('section', entry.notePath, entry.headingPath) : null,
207
+ score,
208
+ reason: REASON.test(entry.reason) ? entry.reason : null,
209
+ matched: null,
210
+ current: null,
211
+ });
212
+ }
213
+ }
214
+ return rows;
215
+ }
216
+ function recordRetrieval(log, ctx, base, args, reply, ms, trace) {
217
+ const query = typeof args.query === 'string' && args.query.trim() !== '' ? args.query : null;
218
+ const relevance = isRecord(reply.body.relevance) ? reply.body.relevance : null;
219
+ const model = ctx.model();
220
+ const candidates = candidateRows(log, servedOf(log, base.tool, reply.body), trace);
221
+ log.recordRetrieval({
222
+ tool: base.tool,
223
+ actor: base.actor,
224
+ sessionKey: base.sessionKey,
225
+ agentKey: base.agentKey,
226
+ queryKey: query === null ? null : log.key('query', norm(query)),
227
+ // The store keeps this only when the log was opened with rawQueries and the secret scanner passes it (store.ts).
228
+ queryText: query,
229
+ queryRedacted: false,
230
+ scopeKey: log.key('scope', (0, scope_1.normalizeScope)(typeof args.scope === 'string' ? args.scope : undefined)),
231
+ retrieval: typeof reply.body.retrieval === 'string' && RETRIEVAL_MODES.includes(reply.body.retrieval) ? reply.body.retrieval : null,
232
+ ranker: schema_1.RANKER_BASELINE,
233
+ model: model !== null && MODEL.test(model) ? model : null,
234
+ build: buildCommit(),
235
+ candidates,
236
+ ms,
237
+ replyTokens: (0, agentMemory_1.replyTokens)(reply.text),
238
+ relevant: relevance !== null && typeof relevance.relevant === 'boolean' ? relevance.relevant : null,
239
+ truncated: typeof reply.body.truncated === 'boolean' ? reply.body.truncated : null,
240
+ leanItems: (0, agentMemory_1.contextLeanItemsEnabled)(),
241
+ });
242
+ if (ctx.sharing && ctx.sharing.level() === 'data') {
243
+ if (query !== null)
244
+ ctx.sharing.query(log.key('query', norm(query)), query);
245
+ for (const candidate of candidates) {
246
+ if (candidate.memoryKey !== null && candidate.text)
247
+ ctx.sharing.memory(candidate.memoryKey, candidate.text);
248
+ }
249
+ }
250
+ }
251
+ function recordOp(log, base, op, kind, memoryKey, subjectKey, replacedKey = null) {
252
+ log.recordMemoryOp({ actor: base.actor, sessionKey: base.sessionKey, agentKey: base.agentKey, tool: base.tool, ms: base.ms,
253
+ op, kind, memoryKey, subjectKey, replacedKey });
254
+ }
255
+ /**
256
+ * A fact save (save_memory, or remember with subject, predicate and object): the value of one subject, predicate and scope.
257
+ * A supersede is recorded as the operation it is, with the value it replaces. It is not a use of any earlier read: the product's
258
+ * usage signal counts it as one (readUsefulness.ts, `updated`), and this log does not.
259
+ */
260
+ function factSave(log, ctx, base, action, scope, subject, predicate, object) {
261
+ if (typeof subject !== 'string' || typeof predicate !== 'string')
262
+ return;
263
+ if (action !== 'store' && action !== 'supersede')
264
+ return; // nochange: nothing was written
265
+ const normalized = (0, scope_1.normalizeScope)(typeof scope === 'string' ? scope : undefined);
266
+ const memoryKey = log.key('fact', normalized, norm(subject), norm(predicate));
267
+ const subjectKey = log.key('subject', normalized, norm(subject));
268
+ if (typeof object === 'string' && ctx.sharing && ctx.sharing.level() === 'data')
269
+ ctx.sharing.memory(memoryKey, `${subject} ${predicate}: ${object}`);
270
+ if (action === 'supersede')
271
+ recordOp(log, base, 'supersede', 'fact', memoryKey, subjectKey, memoryKey);
272
+ else
273
+ recordOp(log, base, 'create', 'fact', memoryKey, subjectKey);
274
+ }
275
+ /** A note save (remember or remember_note): the note is created, or it replaces the memory named by `replaces`. */
276
+ function noteSave(log, ctx, base, file, replaces, text) {
277
+ if (typeof file !== 'string' || file === '')
278
+ return;
279
+ const memoryKey = log.key('note', file);
280
+ if (typeof text === 'string' && ctx.sharing && ctx.sharing.level() === 'data')
281
+ ctx.sharing.memory(memoryKey, text);
282
+ const replaced = typeof replaces === 'string' ? identityOf(log, replaces).memoryKey : null;
283
+ if (replaced !== null)
284
+ recordOp(log, base, 'supersede', 'note', memoryKey, null, replaced);
285
+ else
286
+ recordOp(log, base, 'create', 'note', memoryKey, null);
287
+ }
288
+ function recordWrite(log, ctx, base, args, body) {
289
+ if (schema_1.SAVE_TOOLS.includes(base.tool) && Array.isArray(args.cites)) {
290
+ const scope = (0, scope_1.normalizeScope)(typeof args.scope === 'string' ? args.scope : undefined);
291
+ for (const cite of args.cites.filter((value) => typeof value === 'string').slice(0, MAX_CITES)) {
292
+ const named = citeOf(log, cite, scope);
293
+ log.recordFeedback({
294
+ actor: base.actor, sessionKey: base.sessionKey, agentKey: base.agentKey, tool: base.tool,
295
+ target: named.target, memoryKey: named.memoryKey, subjectKey: named.subjectKey,
296
+ });
297
+ }
298
+ }
299
+ switch (base.tool) {
300
+ case 'save_memory':
301
+ factSave(log, ctx, base, body.action, args.scope, args.subject, args.predicate, args.object);
302
+ return;
303
+ case 'remember':
304
+ if (body.mode === 'fact')
305
+ factSave(log, ctx, base, body.action, args.scope, args.subject, args.predicate, args.object);
306
+ else
307
+ noteSave(log, ctx, base, body.file, args.replaces, args.statement);
308
+ return;
309
+ case 'remember_note':
310
+ noteSave(log, ctx, base, body.file, args.replaces, args.text);
311
+ return;
312
+ case 'retire_memory': {
313
+ if (typeof args.id !== 'string')
314
+ return;
315
+ const named = identityOf(log, args.id);
316
+ if (body.action === 'retired')
317
+ recordOp(log, base, 'delete', named.kind, named.memoryKey, null);
318
+ else if (body.action === 'restored')
319
+ recordOp(log, base, 'restore', named.kind, named.memoryKey, null);
320
+ return;
321
+ }
322
+ case 'restore_memory':
323
+ case 'delete_retired_memory':
324
+ case 'read_memory': {
325
+ if (typeof args.id !== 'string')
326
+ return;
327
+ if (base.tool === 'delete_retired_memory') {
328
+ const erased = Array.isArray(body.ids) ? body.ids.filter((id) => typeof id === 'string') : [args.id];
329
+ for (const id of erased) {
330
+ const named = identityOf(log, id);
331
+ if (named.memoryKey !== null)
332
+ log.eraseMemory(named.memoryKey);
333
+ recordOp(log, base, 'erase', named.kind, null, null);
334
+ }
335
+ return;
336
+ }
337
+ const named = identityOf(log, args.id);
338
+ const op = base.tool === 'restore_memory' ? 'restore' : 'retrieve';
339
+ recordOp(log, base, op, named.kind, named.memoryKey, null);
340
+ return;
341
+ }
342
+ default:
343
+ }
344
+ }
345
+ /** Records one call. Never throws: a failure to write is dropped, and the call it describes has already happened. */
346
+ function observeTool(log, ctx, tool, rawArgs, result, ok, ms, extra, trace) {
347
+ try {
348
+ if (!ok)
349
+ return;
350
+ const retrieval = schema_1.RETRIEVAL_TOOLS.includes(tool);
351
+ const write = schema_1.WRITE_TOOLS.includes(tool);
352
+ if (!retrieval && !write)
353
+ return;
354
+ const reply = replyOf(result);
355
+ if (reply === null)
356
+ return;
357
+ const args = isRecord(rawArgs) ? rawArgs : {};
358
+ const base = {
359
+ actor: ctx.actor,
360
+ sessionKey: ctx.session === null ? null : log.key('session', ctx.session),
361
+ agentKey: log.key('agent', ctx.agent(extra)),
362
+ tool,
363
+ ms,
364
+ };
365
+ if (retrieval)
366
+ recordRetrieval(log, ctx, base, args, reply, ms, trace);
367
+ else
368
+ recordWrite(log, ctx, base, args, reply.body);
369
+ }
370
+ catch {
371
+ // Recording must never fail the call it describes.
372
+ }
373
+ }
374
+ /**
375
+ * The observer for one MCP server, or null when the log is off. Off means nothing is opened and no file is made: a server
376
+ * without RENOR_LEARNING_LOG behaves exactly as it did before this module existed. With a sharing hook the observer exists
377
+ * and decides at each call: a user who chose to share turns recording on, with no restart.
378
+ */
379
+ function learningObserver(settings, ctx) {
380
+ if (settings === undefined)
381
+ return null;
382
+ // Without a sharing choice behind it, the log is on or off for the life of the process, as before.
383
+ if (!settings.enabled && !ctx.sharing)
384
+ return null;
385
+ const sharing = ctx.sharing;
386
+ let held = settings.enabled ? (0, store_1.learningLogAt)(settings) : null;
387
+ return {
388
+ observe: (tool, args, result, ok, ms, extra, trace) => {
389
+ // The sharing choice is read at each call: off records nothing and makes no file, anything above it records.
390
+ if (!settings.enabled && (sharing === undefined || sharing.level() === 'off'))
391
+ return;
392
+ try {
393
+ held ??= (0, store_1.learningLogAt)(settings);
394
+ }
395
+ catch {
396
+ return;
397
+ }
398
+ observeTool(held, ctx, tool, args, result, ok, ms, extra, trace);
399
+ },
400
+ };
401
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TOOLS = void 0;
3
+ exports.HANDOFF_TOOL = exports.TOOLS = void 0;
4
4
  exports.createMcpTools = createMcpTools;
5
5
  exports.utf8Lines = utf8Lines;
6
6
  exports.registerMcpHandlers = registerMcpHandlers;
@@ -27,6 +27,8 @@ const sourceName_1 = require("../memory/sourceName");
27
27
  const requestErrors_1 = require("./requestErrors");
28
28
  const sanitize_1 = require("../mvp/sanitize");
29
29
  const factsFirst_1 = require("../retrieval/factsFirst");
30
+ const handoff_1 = require("../memory/handoff");
31
+ const buildIdentity_1 = require("../buildIdentity");
30
32
  function createMcpTools(db, vectorIndex, provider, config, evidence = { mode: 'off', model: '', maxSessions: 12, charCap: 6000 }) {
31
33
  // Startup configuration, captured once: tool arguments and later env changes cannot rename a connection.
32
34
  // The hive name is the header form. Empty, unnamed, or a second live holder publishes no hive tools
@@ -66,8 +68,18 @@ function createMcpTools(db, vectorIndex, provider, config, evidence = { mode: 'o
66
68
  return { warning: 'memory-saved-but-index-refresh-failed', detail: detail.slice(0, 300) };
67
69
  }
68
70
  };
71
+ // The handoff note (memory/handoff.ts), only with RENOR_HANDOFF_NOTE on. Its writer is this connection's startup name;
72
+ // its expiry sweep runs for the life of the process (the timer never keeps it alive).
73
+ if ((0, handoff_1.handoffNoteEnabled)())
74
+ (0, handoff_1.startHandoffSweep)(db);
75
+ const handoff = (0, handoff_1.handoffNoteEnabled)()
76
+ ? { async [handoff_1.HANDOFF_TOOL_NAME](args) {
77
+ return (0, handoff_1.runHandoffTool)(db, args ?? {}, identity ?? 'stdio');
78
+ } }
79
+ : {};
69
80
  return {
70
81
  ...hive,
82
+ ...handoff,
71
83
  // Canonical tool names. Clients that prefix with the server name render
72
84
  // these as renor_search, renor_keyword, renor_facts, etc.
73
85
  async search(args) {
@@ -290,6 +302,21 @@ exports.TOOLS = [
290
302
  },
291
303
  },
292
304
  ];
305
+ /** Listed beside TOOLS only when the server has the handler, i.e. RENOR_HANDOFF_NOTE was on at startup. */
306
+ exports.HANDOFF_TOOL = {
307
+ name: handoff_1.HANDOFF_TOOL_NAME,
308
+ description: handoff_1.HANDOFF_TOOL_DESCRIPTION,
309
+ inputSchema: {
310
+ type: 'object',
311
+ properties: {
312
+ action: { type: 'string', enum: ['read', 'write'], description: handoff_1.HANDOFF_ARG_DESCRIPTIONS.action },
313
+ repo: { type: 'string', description: handoff_1.HANDOFF_ARG_DESCRIPTIONS.repo },
314
+ branch: { type: 'string', description: handoff_1.HANDOFF_ARG_DESCRIPTIONS.branch },
315
+ note: { type: 'string', description: handoff_1.HANDOFF_ARG_DESCRIPTIONS.note },
316
+ },
317
+ required: ['action', 'repo', 'branch'],
318
+ },
319
+ };
293
320
  /**
294
321
  * The stdin of the stdio server as lines the MCP transport can read, with a line that is not valid UTF-8 kept out.
295
322
  *
@@ -338,11 +365,14 @@ function utf8Lines(source, onInvalid) {
338
365
  * the published schema or the error envelope the client actually sees were wrong.
339
366
  */
340
367
  function registerMcpHandlers(server, tools) {
341
- const hive = hive_1.HIVE_TOOLS.filter(tool => typeof tools[tool.name] === 'function');
342
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: [...exports.TOOLS, ...hive] }));
368
+ // Looked up by the name the client sent: an argument shape is the tool's own to check.
369
+ const byName = tools;
370
+ const hive = hive_1.HIVE_TOOLS.filter(tool => typeof byName[tool.name] === 'function');
371
+ const handoff = typeof byName[handoff_1.HANDOFF_TOOL_NAME] === 'function' ? [exports.HANDOFF_TOOL] : [];
372
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: [...exports.TOOLS, ...hive, ...handoff] }));
343
373
  server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
344
374
  const { name, arguments: args } = request.params;
345
- const handler = tools[name];
375
+ const handler = byName[name];
346
376
  if (!handler) {
347
377
  if (hive_1.HIVE_TOOLS.some(tool => tool.name === name)) {
348
378
  return { content: [{ type: 'text', text: `${name} is refused: this connection has no name. Set RENOR_CONNECTION_NAME to this agent's name before starting renor-engine mcp, then reconnect.` }], isError: true };
@@ -357,12 +387,12 @@ function registerMcpHandlers(server, tools) {
357
387
  return { content: [{ type: 'text', text: (0, sanitize_1.escapeInvisibleControls)(JSON.stringify(result)) }] };
358
388
  }
359
389
  catch (err) {
360
- return { content: [{ type: 'text', text: (0, sanitize_1.escapeInvisibleControls)(`Error: ${err.message}`) }], isError: true };
390
+ return { content: [{ type: 'text', text: (0, sanitize_1.escapeInvisibleControls)(`Error: ${err instanceof Error ? err.message : String(err)}`) }], isError: true };
361
391
  }
362
392
  });
363
393
  }
364
394
  async function startMcpServer(db, vectorIndex, provider, config) {
365
- const server = new index_js_1.Server({ name: 'renor', version: '1.0.0' }, { capabilities: { tools: {} } });
395
+ const server = new index_js_1.Server({ name: 'renor', version: buildIdentity_1.ENGINE_VERSION }, { capabilities: { tools: {} } });
366
396
  const evidence = (0, options_1.resolveEvidenceToolOptions)(config);
367
397
  const tools = createMcpTools(db, vectorIndex, provider, config, evidence);
368
398
  registerMcpHandlers(server, tools);