@totalreclaw/mcp-server 3.3.0-rc.2 → 3.3.0-rc.4

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.
@@ -0,0 +1,1257 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP-server - Fact Extractor
4
+ *
5
+ * Ported verbatim from `skill/plugin/extractor.ts` (mcp-server 3.3.0-rc.3,
6
+ * MCP-first autonomous extraction pivot). The plugin file is the canonical
7
+ * source — keep them in sync.
8
+ *
9
+ * Uses LLM calls to extract atomic facts from conversation messages.
10
+ * Matches the extraction prompts described in SKILL.md.
11
+ *
12
+ * Phrase-safety hard rail: this module operates ONLY on the conversation
13
+ * messages handed in by the trajectory poller (user prompts + assistant
14
+ * replies parsed from OpenClaw trajectory JSONL). The recovery phrase
15
+ * NEVER reaches this module — it is used solely by the on-chain submit
16
+ * path (subgraph/store.ts) for HD wallet derivation, in a different
17
+ * call stack. The extraction LLM prompt template is a pure constant;
18
+ * user-supplied content goes through `messageToText` which only reads
19
+ * `role` and `content` fields.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.EXTRACTION_SYSTEM_PROMPT_V1_MERGED = exports.EXTRACTION_SYSTEM_PROMPT = exports.DEBRIEF_SYSTEM_PROMPT = exports.COMPACTION_SYSTEM_PROMPT = exports.DEFAULT_EXTRACTION_CONFIDENCE = exports.V0_TO_V1_TYPE = exports.VALID_MEMORY_VOLATILITIES = exports.VALID_MEMORY_SCOPES = exports.VALID_MEMORY_SOURCES = exports.LEGACY_V0_MEMORY_TYPES = exports.VALID_MEMORY_TYPES_V1 = exports.VALID_MEMORY_TYPES = void 0;
23
+ exports.isValidMemoryType = isValidMemoryType;
24
+ exports.isValidMemoryTypeV1 = isValidMemoryTypeV1;
25
+ exports.parseEntity = parseEntity;
26
+ exports.normalizeConfidence = normalizeConfidence;
27
+ exports.computeLexicalImportanceBump = computeLexicalImportanceBump;
28
+ exports.parseFactsResponseForCompaction = parseFactsResponseForCompaction;
29
+ exports.extractFactsForCompaction = extractFactsForCompaction;
30
+ exports.parseDebriefResponse = parseDebriefResponse;
31
+ exports.extractDebrief = extractDebrief;
32
+ exports.parseMergedResponseV1 = parseMergedResponseV1;
33
+ exports.parseFactsResponse = parseFactsResponse;
34
+ exports.applyProvenanceFilterLax = applyProvenanceFilterLax;
35
+ exports.defaultVolatility = defaultVolatility;
36
+ exports.comparativeRescoreV1 = comparativeRescoreV1;
37
+ exports.extractFacts = extractFacts;
38
+ const llm_client_js_1 = require("./llm-client.js");
39
+ // ---------------------------------------------------------------------------
40
+ // Memory Taxonomy v1 — the 6 canonical memory types. Single source of truth.
41
+ //
42
+ // Plugin v3.0.0 adopts v1 as the ONLY taxonomy. Legacy v0 tokens
43
+ // (fact, decision, episodic, goal, context, rule) are accepted only on the
44
+ // read-side via `LEGACY_V0_MEMORY_TYPES` / `V0_TO_V1_TYPE` and
45
+ // `normalizeToV1Type` in `claims-helper.ts`, so pre-v3 vault entries can
46
+ // still be decoded. Extraction and write paths emit v1 exclusively.
47
+ //
48
+ // When adding a new type, update ALL of:
49
+ // - This constant
50
+ // - `mcp/src/v1-types.ts`
51
+ // - `python/src/totalreclaw/agent/extraction.py`
52
+ // - `rust/totalreclaw-core/src/claims.rs`
53
+ // - `skill/plugin/claims-helper.ts`
54
+ // - The `EXTRACTION_SYSTEM_PROMPT` Types: list
55
+ // ---------------------------------------------------------------------------
56
+ exports.VALID_MEMORY_TYPES = [
57
+ 'claim',
58
+ 'preference',
59
+ 'directive',
60
+ 'commitment',
61
+ 'episode',
62
+ 'summary',
63
+ ];
64
+ /**
65
+ * Runtime type guard — returns whether an unknown value is a valid v1
66
+ * `MemoryType`. Legacy v0 tokens return `false`; use `normalizeToV1Type()`
67
+ * in `claims-helper.ts` to coerce them on the read path.
68
+ */
69
+ function isValidMemoryType(value) {
70
+ return typeof value === 'string' && exports.VALID_MEMORY_TYPES.includes(value);
71
+ }
72
+ /**
73
+ * Backward-compat alias. Same list as `VALID_MEMORY_TYPES`.
74
+ * @deprecated Use `VALID_MEMORY_TYPES` instead.
75
+ */
76
+ exports.VALID_MEMORY_TYPES_V1 = exports.VALID_MEMORY_TYPES;
77
+ /**
78
+ * Backward-compat alias. Same guard as `isValidMemoryType`.
79
+ * @deprecated Use `isValidMemoryType` instead.
80
+ */
81
+ function isValidMemoryTypeV1(value) {
82
+ return isValidMemoryType(value);
83
+ }
84
+ /**
85
+ * Legacy v0 memory types — retained as a typed constant so the read-side
86
+ * `V0_TO_V1_TYPE` mapping can reference them without redeclaration.
87
+ *
88
+ * Do NOT emit these on the write/extraction path. They exist solely so
89
+ * `claims-helper.ts::readClaimFromBlob` can decode pre-v1 vault entries
90
+ * whose encrypted blobs still carry v0 token strings.
91
+ */
92
+ exports.LEGACY_V0_MEMORY_TYPES = [
93
+ 'fact',
94
+ 'preference',
95
+ 'decision',
96
+ 'episodic',
97
+ 'goal',
98
+ 'context',
99
+ 'summary',
100
+ 'rule',
101
+ ];
102
+ exports.VALID_MEMORY_SOURCES = [
103
+ 'user',
104
+ 'user-inferred',
105
+ 'assistant',
106
+ 'external',
107
+ 'derived',
108
+ ];
109
+ exports.VALID_MEMORY_SCOPES = [
110
+ 'work',
111
+ 'personal',
112
+ 'health',
113
+ 'family',
114
+ 'creative',
115
+ 'finance',
116
+ 'misc',
117
+ 'unspecified',
118
+ ];
119
+ exports.VALID_MEMORY_VOLATILITIES = [
120
+ 'stable',
121
+ 'updatable',
122
+ 'ephemeral',
123
+ ];
124
+ /**
125
+ * Legacy v0 → v1 type mapping used by the read-side adapter when decoding
126
+ * a pre-v1 vault entry that still carries a v0 token string.
127
+ *
128
+ * Decisions (v0) map to v1 `claim` — the reasoning lives in the separate
129
+ * `reasoning` field rather than being encoded in the type.
130
+ */
131
+ exports.V0_TO_V1_TYPE = {
132
+ fact: 'claim',
133
+ preference: 'preference',
134
+ decision: 'claim',
135
+ episodic: 'episode',
136
+ goal: 'commitment',
137
+ context: 'claim',
138
+ summary: 'summary',
139
+ rule: 'directive',
140
+ };
141
+ const ALLOWED_ENTITY_TYPES = new Set([
142
+ 'person',
143
+ 'project',
144
+ 'tool',
145
+ 'company',
146
+ 'concept',
147
+ 'place',
148
+ ]);
149
+ /**
150
+ * Default confidence when the LLM does not provide one.
151
+ * Mirrors the fallback used by other extraction clients.
152
+ */
153
+ exports.DEFAULT_EXTRACTION_CONFIDENCE = 0.85;
154
+ // ---------------------------------------------------------------------------
155
+ // Helpers
156
+ // ---------------------------------------------------------------------------
157
+ /**
158
+ * Extract text content from a conversation message (handles various formats).
159
+ *
160
+ * OpenClaw AgentMessage objects use content arrays:
161
+ * { role: "user", content: [{ type: "text", text: "..." }] }
162
+ * { role: "assistant", content: [{ type: "text", text: "..." }, { type: "toolCall", ... }] }
163
+ *
164
+ * We also handle the simpler { role, content: "string" } format.
165
+ */
166
+ function messageToText(msg) {
167
+ if (!msg || typeof msg !== 'object')
168
+ return null;
169
+ const m = msg;
170
+ const role = m.role ?? 'unknown';
171
+ // Only keep user and assistant messages
172
+ if (role !== 'user' && role !== 'assistant')
173
+ return null;
174
+ let textContent;
175
+ if (typeof m.content === 'string') {
176
+ // Simple string content
177
+ textContent = m.content;
178
+ }
179
+ else if (Array.isArray(m.content)) {
180
+ // OpenClaw AgentMessage format: array of content blocks
181
+ // Extract text from { type: "text", text: "..." } blocks
182
+ const textParts = m.content
183
+ .filter((block) => block.type === 'text' && typeof block.text === 'string')
184
+ .map((block) => block.text);
185
+ textContent = textParts.join('\n');
186
+ }
187
+ else if (typeof m.text === 'string') {
188
+ // Fallback: { text: "..." } field
189
+ textContent = m.text;
190
+ }
191
+ else {
192
+ return null;
193
+ }
194
+ if (textContent.length < 3)
195
+ return null;
196
+ return { role, content: textContent };
197
+ }
198
+ /**
199
+ * Truncate messages to fit within a token budget (rough estimate: 4 chars per token).
200
+ */
201
+ function truncateMessages(messages, maxChars) {
202
+ const lines = [];
203
+ let totalChars = 0;
204
+ for (const msg of messages) {
205
+ const line = `[${msg.role}]: ${msg.content}`;
206
+ if (totalChars + line.length > maxChars)
207
+ break;
208
+ lines.push(line);
209
+ totalChars += line.length;
210
+ }
211
+ return lines.join('\n\n');
212
+ }
213
+ /**
214
+ * Parse a single entity object from LLM output. Returns null if invalid.
215
+ * Invalid entities are silently dropped so a bad entity never fails the whole fact.
216
+ */
217
+ function parseEntity(raw) {
218
+ if (!raw || typeof raw !== 'object')
219
+ return null;
220
+ const e = raw;
221
+ const name = typeof e.name === 'string' ? e.name.trim() : '';
222
+ if (name.length === 0)
223
+ return null;
224
+ const type = String(e.type ?? '').toLowerCase();
225
+ if (!ALLOWED_ENTITY_TYPES.has(type))
226
+ return null;
227
+ const entity = { name: name.slice(0, 128), type };
228
+ if (typeof e.role === 'string' && e.role.trim().length > 0) {
229
+ entity.role = e.role.trim().slice(0, 128);
230
+ }
231
+ return entity;
232
+ }
233
+ /**
234
+ * Clamp a raw confidence value to [0, 1]. Returns the default when missing or NaN.
235
+ */
236
+ function normalizeConfidence(raw) {
237
+ if (typeof raw !== 'number' || !Number.isFinite(raw))
238
+ return exports.DEFAULT_EXTRACTION_CONFIDENCE;
239
+ if (raw < 0)
240
+ return 0;
241
+ if (raw > 1)
242
+ return 1;
243
+ return raw;
244
+ }
245
+ // ---------------------------------------------------------------------------
246
+ // Phase 2.2.6: lexical importance bumps
247
+ // ---------------------------------------------------------------------------
248
+ /**
249
+ * Escape regex metacharacters so a string can be used as a literal pattern.
250
+ */
251
+ function escapeRegExp(s) {
252
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
253
+ }
254
+ /**
255
+ * Compute a lexical importance bump (0-2) for a single fact based on signals
256
+ * in the surrounding conversation text.
257
+ *
258
+ * This is a Phase 2.2.6 quality fix complementing the prompt rubric tightening
259
+ * (item A). Where the rubric tells the LLM to use the full 1-10 range, the
260
+ * bump tells us *as a post-process*: when the user's actual phrasing carries
261
+ * strong "remember this" signals that the LLM may have under-weighted, push
262
+ * the score up.
263
+ *
264
+ * Signals detected (each adds +1, capped at +2 total):
265
+ *
266
+ * 1. **Strong intent phrases** anywhere in the conversation:
267
+ * "remember this", "never forget", "rule of thumb", "critical",
268
+ * "don't ever forget", explicit "always X" / "never Y" patterns.
269
+ * 2. **Emphasis markers**: `!!` (double exclamation), or 3+ all-caps words
270
+ * in a row (e.g. "DO NOT FORGET", "VERY IMPORTANT").
271
+ * 3. **Repetition**: the fact's first ~20 chars appear at least twice in
272
+ * the conversation text (paraphrased restating).
273
+ *
274
+ * The bump is additive on top of whatever the LLM scored; final importance
275
+ * is capped at 10.
276
+ *
277
+ * Final-importance ceiling: this never makes a fact pass the importance >= 6
278
+ * filter on its own — a fact still needs to have an LLM score >= 5 (because
279
+ * +2 from 5 = 7, above floor; +1 from 5 = 6, above floor). This is intentional:
280
+ * the bump is for "the LLM correctly identified this as worth storing but
281
+ * under-weighted it", not "the LLM said skip but we're overriding."
282
+ */
283
+ function computeLexicalImportanceBump(factText, conversationText) {
284
+ let bump = 0;
285
+ const lowerConv = conversationText.toLowerCase();
286
+ // Signal 1: strong intent phrases anywhere in the conversation
287
+ const strongIntent = /\b(remember this|never forget|rule of thumb|don't (?:ever )?forget|critical|important|gotcha|note to self)\b/i;
288
+ if (strongIntent.test(lowerConv))
289
+ bump += 1;
290
+ // Signal 2: emphasis markers — double exclamation OR 3+ consecutive all-caps words
291
+ // (3+ chars each, to avoid false positives on acronyms like "AWS S3 IAM")
292
+ const doubleExclamation = /!!/;
293
+ const allCapsPhrase = /\b[A-Z]{3,}(?:\s+[A-Z]{3,}){2,}\b/;
294
+ if (doubleExclamation.test(conversationText) || allCapsPhrase.test(conversationText)) {
295
+ bump += 1;
296
+ }
297
+ // Signal 3: repetition — extract content words (length >= 5, not common stop
298
+ // words) from the fact, and check if any single one appears 2+ times in the
299
+ // conversation. This is more robust to LLM paraphrasing than a fingerprint
300
+ // match: "User prefers PostgreSQL" extracted from "I prefer PostgreSQL ...
301
+ // yeah PostgreSQL is right for OLTP" still triggers because "postgresql"
302
+ // appears multiple times even though the leading chars differ.
303
+ const lowerFact = factText.toLowerCase();
304
+ const stopWords = new Set([
305
+ 'about', 'after', 'again', 'against', 'because', 'before', 'being',
306
+ 'between', 'could', 'doing', 'during', 'every', 'further', 'having',
307
+ 'their', 'these', 'those', 'through', 'under', 'until', 'where', 'which',
308
+ 'while', 'would', 'should', 'about', 'thing', 'things', 'something',
309
+ 'someone', 'always', 'never', 'often', 'still', 'really', 'maybe',
310
+ 'using', 'works', 'work', 'user', 'users', 'with', 'from', 'into',
311
+ 'like', 'just', 'than', 'them', 'they', 'will', 'when', 'what', 'were',
312
+ 'this', 'that', 'have', 'this',
313
+ ]);
314
+ const factWords = lowerFact.split(/[^a-z0-9_]+/).filter((w) => w.length >= 5 && !stopWords.has(w));
315
+ let triggered = false;
316
+ for (const word of factWords) {
317
+ const occurrences = (lowerConv.match(new RegExp(`\\b${escapeRegExp(word)}\\b`, 'g')) || [])
318
+ .length;
319
+ if (occurrences >= 2) {
320
+ triggered = true;
321
+ break;
322
+ }
323
+ }
324
+ if (triggered)
325
+ bump += 1;
326
+ return Math.min(bump, 2);
327
+ }
328
+ // ---------------------------------------------------------------------------
329
+ // Compaction-Aware Extraction (Phase 2.3)
330
+ // ---------------------------------------------------------------------------
331
+ /**
332
+ * Compaction-specific system prompt (v1 taxonomy). Fires when the conversation
333
+ * context is about to be compacted. LAST CHANCE to capture knowledge before
334
+ * it is lost, so the importance floor is 5 instead of 6 and the prompt is
335
+ * more aggressive about extracting active-project context, claims, and
336
+ * episodes.
337
+ *
338
+ * Differences from `EXTRACTION_SYSTEM_PROMPT`:
339
+ * - Opening framing emphasizes urgency ("last chance")
340
+ * - Format-agnostic: handles bullet lists, prose, mixed formats
341
+ * - Importance threshold lowered to 5
342
+ * - More aggressive on claim / episode / directive types
343
+ * - Anti-pattern: don't skip content just because it's in a summary
344
+ *
345
+ * Output format matches `EXTRACTION_SYSTEM_PROMPT` exactly (same merged
346
+ * topics+facts JSON shape with v1 type / source / scope fields), so the
347
+ * same `parseMergedResponseV1` parser can validate it.
348
+ */
349
+ exports.COMPACTION_SYSTEM_PROMPT = `You are extracting memories from a conversation that is about to be compacted. The context will be LOST after this point — this is your LAST CHANCE to capture everything worth remembering. Be more aggressive than usual: err on the side of storing.
350
+
351
+ Work in TWO explicit phases within one response:
352
+
353
+ PHASE 1 — Topic identification.
354
+ Identify the 2-3 main topics the user was engaging with before extracting any fact. Topics should be short phrases (2-5 words each). If there's no clear user-focused topic, use an empty topics array.
355
+
356
+ PHASE 2 — Fact extraction anchored to those topics (plus preserve active context).
357
+ Extract valuable memories. Prefer facts that directly relate to the identified topics (importance 7-9 range). Active project context, decisions in progress, and current working state score 6-8 during compaction — capture them even when they'd normally be marginal.
358
+
359
+ Rules:
360
+ 1. Each memory = single self-contained piece of information
361
+ 2. Focus on user-specific info useful in future conversations
362
+ 3. Skip generic knowledge, greetings, small talk
363
+ 4. Score importance 1-10 (5+ = worth storing during compaction)
364
+ 5. Every memory MUST attribute a source (provenance critical)
365
+
366
+ Importance rubric (full 1-10 range, NOT just 7-8):
367
+ - 10: Core identity, never-forget ("remember this forever", name/birthday)
368
+ - 9: Affects many future decisions / high-impact rules
369
+ - 8: Preference / decision-with-reasoning / operational rule
370
+ - 7: Specific durable fact
371
+ - 6: Borderline — during compaction, capture anyway
372
+ - 5: Would normally drop; keep as compaction safety net
373
+ - 4 or below: DROP (greetings, filler)
374
+
375
+ ═══════════════════════════════════════════════════════════════
376
+ TYPE (6 values)
377
+ ═══════════════════════════════════════════════════════════════
378
+ - claim: factual assertion (absorbs v0 fact/context/decision; decisions populate reasoning)
379
+ - preference: likes/dislikes/tastes
380
+ - directive: imperative rule ("always X", "never Y")
381
+ - commitment: future intent ("will do X")
382
+ - episode: notable event
383
+ - summary: derived synthesis (source must be derived|assistant)
384
+
385
+ ═══════════════════════════════════════════════════════════════
386
+ SOURCE (provenance, CRITICAL)
387
+ ═══════════════════════════════════════════════════════════════
388
+ - user: user explicitly stated it (in [user]: turns)
389
+ - user-inferred: extractor inferred from user signals
390
+ - assistant: assistant authored — DOWNGRADE unless user affirmed/quoted
391
+ - external, derived: rare
392
+
393
+ IF fact substance appears ONLY in [assistant]: turns without user affirmation → source:assistant.
394
+
395
+ ═══════════════════════════════════════════════════════════════
396
+ SCOPE
397
+ ═══════════════════════════════════════════════════════════════
398
+ work | personal | health | family | creative | finance | misc | unspecified
399
+
400
+ ═══════════════════════════════════════════════════════════════
401
+ ENTITIES
402
+ ═══════════════════════════════════════════════════════════════
403
+ - type ∈ {person, project, tool, company, concept, place}
404
+ - prefer specific names ("PostgreSQL" not "database")
405
+ - omit umbrella categories when specific name is present
406
+
407
+ ═══════════════════════════════════════════════════════════════
408
+ REASONING (only for claims that are decisions)
409
+ ═══════════════════════════════════════════════════════════════
410
+ For type=claim where the user expressed a decision-with-reasoning, populate "reasoning" with the WHY clause.
411
+
412
+ ═══════════════════════════════════════════════════════════════
413
+ FORMAT-AGNOSTIC PARSING (IMPORTANT)
414
+ ═══════════════════════════════════════════════════════════════
415
+ The conversation may contain bullet lists, numbered lists, section headers, code snippets, or plain prose. Treat ALL formats as potential sources of extractable memory:
416
+ - Bullets/list items: each item is a candidate.
417
+ - Section headers (Context, Decisions, Key Learnings, Open Questions): use the header as a TYPE HINT (Context → claim, Decisions → claim+reasoning, Learnings → directive, Open Questions → commitment).
418
+ - Plain prose: parse each distinct assertion as a candidate.
419
+ - Code snippets: extract config choices, tool versions, architectural decisions embedded in comments or structure.
420
+ - Mixed format: apply all of the above.
421
+
422
+ Do NOT skip content just because it's in a summary. The agent has already filtered — your job is to convert into structured memories, not to re-evaluate worth.
423
+
424
+ ═══════════════════════════════════════════════════════════════
425
+ OUTPUT FORMAT (no markdown, no code fences)
426
+ ═══════════════════════════════════════════════════════════════
427
+ {
428
+ "topics": ["topic 1", "topic 2"],
429
+ "facts": [
430
+ {
431
+ "text": "...",
432
+ "type": "claim|preference|directive|commitment|episode",
433
+ "source": "user|user-inferred|assistant",
434
+ "scope": "work|personal|health|...",
435
+ "importance": N,
436
+ "confidence": 0.9,
437
+ "action": "ADD",
438
+ "reasoning": "...", // optional, only for claim+decision
439
+ "entities": [{"name": "...", "type": "tool"}]
440
+ }
441
+ ]
442
+ }
443
+
444
+ If nothing worth extracting: {"topics": [], "facts": []}`;
445
+ /**
446
+ * Parse facts for compaction context (v1 taxonomy; importance floor 5).
447
+ *
448
+ * Identical to `parseFactsResponse` except the importance floor is 5 instead
449
+ * of 6 — compaction is the last chance to capture context, so we accept
450
+ * borderline facts that would normally be dropped.
451
+ *
452
+ * Accepts the same merged-topic v1 JSON shape as the main prompt. The
453
+ * inner `parseMergedResponseV1` enforces the >=6 floor, so we re-run a
454
+ * lenient >=5 pass on the raw parsed payload to admit the borderline items.
455
+ */
456
+ function parseFactsResponseForCompaction(response, logger) {
457
+ const originalPreview = response.trim().slice(0, 200);
458
+ let cleaned = response.trim();
459
+ // Strip <think>...</think> and <thinking>...</thinking> tags
460
+ cleaned = cleaned
461
+ .replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '')
462
+ .trim();
463
+ // Strip markdown code fences if present
464
+ if (cleaned.startsWith('```')) {
465
+ cleaned = cleaned.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();
466
+ }
467
+ const tryParse = (input) => {
468
+ try {
469
+ return JSON.parse(input);
470
+ }
471
+ catch {
472
+ return undefined;
473
+ }
474
+ };
475
+ let parsed = tryParse(cleaned);
476
+ let recoveryUsed = 'none';
477
+ if (parsed === undefined) {
478
+ // Try bare-array first (legacy compaction output), then object (v1 merged).
479
+ const arrMatch = cleaned.match(/\[[\s\S]*\]/);
480
+ if (arrMatch) {
481
+ parsed = tryParse(arrMatch[0]);
482
+ if (parsed !== undefined)
483
+ recoveryUsed = 'bracket-scan';
484
+ }
485
+ if (parsed === undefined) {
486
+ const objMatch = cleaned.match(/\{[\s\S]*\}/);
487
+ if (objMatch) {
488
+ parsed = tryParse(objMatch[0]);
489
+ if (parsed !== undefined)
490
+ recoveryUsed = 'bracket-scan';
491
+ }
492
+ }
493
+ }
494
+ if (recoveryUsed === 'bracket-scan') {
495
+ logger?.info?.(`parseFactsResponseForCompaction: recovered JSON via bracket-scan fallback`);
496
+ }
497
+ if (!parsed || typeof parsed !== 'object') {
498
+ logger?.warn?.(`parseFactsResponseForCompaction: could not parse LLM output as JSON object. Preview: ${JSON.stringify(originalPreview)}`);
499
+ return [];
500
+ }
501
+ const obj = parsed;
502
+ const rawFacts = Array.isArray(obj.facts) ? obj.facts : null;
503
+ // Legacy v0 compaction output (bare JSON array) — best-effort parse.
504
+ const rawArray = rawFacts ?? (Array.isArray(parsed) ? parsed : null);
505
+ if (!rawArray) {
506
+ logger?.warn?.(`parseFactsResponseForCompaction: expected { facts: [...] } object, got ${typeof parsed}`);
507
+ return [];
508
+ }
509
+ const validActions = ['ADD', 'UPDATE', 'DELETE', 'NOOP'];
510
+ const facts = rawArray
511
+ .filter((f) => !!f &&
512
+ typeof f === 'object' &&
513
+ typeof f.text === 'string' &&
514
+ f.text.length >= 5)
515
+ .map((f) => {
516
+ const rawType = String(f.type ?? 'claim').toLowerCase();
517
+ // Accept v1 tokens directly; coerce legacy v0 tokens via V0_TO_V1_TYPE.
518
+ let type;
519
+ if (isValidMemoryType(rawType)) {
520
+ type = rawType;
521
+ }
522
+ else if (exports.LEGACY_V0_MEMORY_TYPES.includes(rawType)) {
523
+ type = exports.V0_TO_V1_TYPE[rawType];
524
+ }
525
+ else {
526
+ type = 'claim';
527
+ }
528
+ const rawSource = String(f.source ?? 'user-inferred').toLowerCase();
529
+ const source = exports.VALID_MEMORY_SOURCES.includes(rawSource)
530
+ ? rawSource
531
+ : 'user-inferred';
532
+ const rawScope = String(f.scope ?? 'unspecified').toLowerCase();
533
+ const scope = exports.VALID_MEMORY_SCOPES.includes(rawScope)
534
+ ? rawScope
535
+ : 'unspecified';
536
+ const reasoning = typeof f.reasoning === 'string' ? f.reasoning.slice(0, 256) : undefined;
537
+ const action = validActions.includes(String(f.action))
538
+ ? String(f.action)
539
+ : 'ADD';
540
+ let entities;
541
+ if (Array.isArray(f.entities)) {
542
+ const valid = f.entities
543
+ .map(parseEntity)
544
+ .filter((e) => e !== null);
545
+ if (valid.length > 0)
546
+ entities = valid;
547
+ }
548
+ const result = {
549
+ text: String(f.text).slice(0, 512),
550
+ type,
551
+ source,
552
+ scope,
553
+ reasoning,
554
+ importance: Math.max(1, Math.min(10, Number(f.importance) || 5)),
555
+ action,
556
+ existingFactId: typeof f.existingFactId === 'string' ? f.existingFactId : undefined,
557
+ confidence: normalizeConfidence(f.confidence),
558
+ };
559
+ if (entities)
560
+ result.entities = entities;
561
+ return result;
562
+ })
563
+ // Reject illegal type:summary + source:user
564
+ .filter((f) => !(f.type === 'summary' && f.source === 'user'))
565
+ // Compaction: importance >= 5 (not 6)
566
+ .filter((f) => f.importance >= 5 || f.action === 'DELETE');
567
+ return facts;
568
+ }
569
+ /**
570
+ * Extract facts using the compaction-aware prompt.
571
+ *
572
+ * This is called from the `before_compaction` hook — the LAST CHANCE to
573
+ * capture knowledge before conversation context is lost. Key differences
574
+ * from `extractFacts`:
575
+ * - Uses `COMPACTION_SYSTEM_PROMPT` (lower threshold, format-agnostic, more aggressive)
576
+ * - Always processes the full conversation (`mode: 'full'`)
577
+ * - Importance filter is >= 5 instead of >= 6
578
+ * - Lexical importance bumps still apply
579
+ *
580
+ * @param rawMessages - The messages array from the hook event (unknown[])
581
+ * @param existingMemories - Optional list of existing memories for dedup context
582
+ * @param logger - Optional logger for observability
583
+ * @returns Array of extracted facts, or empty array on failure.
584
+ */
585
+ async function extractFactsForCompaction(rawMessages, existingMemories, logger) {
586
+ const config = (0, llm_client_js_1.resolveLLMConfig)();
587
+ if (!config) {
588
+ logger?.info?.('extractFactsForCompaction: no LLM config resolved (skipping extraction)');
589
+ return [];
590
+ }
591
+ // Parse messages
592
+ const parsed = rawMessages
593
+ .map(messageToText)
594
+ .filter((m) => m !== null);
595
+ if (parsed.length === 0) {
596
+ logger?.info?.(`extractFactsForCompaction: no parseable messages (raw count=${rawMessages.length})`);
597
+ return [];
598
+ }
599
+ // Always full mode — process entire conversation for compaction
600
+ const conversationText = truncateMessages(parsed, 12_000);
601
+ if (conversationText.length < 20) {
602
+ logger?.info?.(`extractFactsForCompaction: conversation too short (${conversationText.length} chars < 20)`);
603
+ return [];
604
+ }
605
+ // Build existing memories context if available
606
+ let memoriesContext = '';
607
+ if (existingMemories && existingMemories.length > 0) {
608
+ const memoriesStr = existingMemories
609
+ .map((m) => `[ID: ${m.id}] ${m.text}`)
610
+ .join('\n');
611
+ memoriesContext = `\n\nExisting memories (use these for dedup — classify as UPDATE/DELETE/NOOP if they conflict or overlap):\n${memoriesStr}`;
612
+ }
613
+ const userPrompt = `Extract ALL valuable long-term memories from this conversation before it is compacted and lost:\n\n${conversationText}${memoriesContext}`;
614
+ let response;
615
+ try {
616
+ response = await (0, llm_client_js_1.chatCompletion)(config, [
617
+ { role: 'system', content: exports.COMPACTION_SYSTEM_PROMPT },
618
+ { role: 'user', content: userPrompt },
619
+ ], {
620
+ // 3.3.1-rc.2: retry transient 429 / timeout (same policy as extractFacts).
621
+ retry: { attempts: 3, baseDelayMs: 1000 },
622
+ timeoutMs: 30_000,
623
+ logger,
624
+ });
625
+ }
626
+ catch (err) {
627
+ const msg = err instanceof Error ? err.message : String(err);
628
+ logger?.warn?.(`extractFactsForCompaction: chatCompletion threw: ${msg}`);
629
+ return [];
630
+ }
631
+ if (!response) {
632
+ logger?.info?.('extractFactsForCompaction: chatCompletion returned null/empty response');
633
+ return [];
634
+ }
635
+ logger?.info?.(`extractFactsForCompaction: LLM returned ${response.length} chars; handing to parseFactsResponseForCompaction`);
636
+ let facts = parseFactsResponseForCompaction(response, logger);
637
+ // v1 provenance filter (tag-don't-drop). Uses importance >= 5 floor because
638
+ // the filter's own floor is 5 in lax mode, matching compaction semantics.
639
+ facts = applyProvenanceFilterLax(facts, conversationText);
640
+ // Comparative rescore if >= 5 facts (same as default pipeline), else
641
+ // assign defaultVolatility so v1 write path has a value.
642
+ facts = await comparativeRescoreV1(facts, conversationText, logger);
643
+ facts = facts.map((f) => ({ ...f, volatility: f.volatility ?? defaultVolatility(f) }));
644
+ // Lexical importance bumps (same as regular extraction)
645
+ for (const f of facts) {
646
+ const bump = computeLexicalImportanceBump(f.text, conversationText);
647
+ if (bump > 0) {
648
+ const oldImportance = f.importance;
649
+ const effectiveBump = f.importance >= 8 ? Math.min(bump, 1) : bump;
650
+ f.importance = Math.min(10, f.importance + effectiveBump);
651
+ logger?.info?.(`extractFactsForCompaction: lexical bump +${bump} for "${f.text.slice(0, 60)}..." (${oldImportance} → ${f.importance})`);
652
+ }
653
+ }
654
+ return facts;
655
+ }
656
+ // ---------------------------------------------------------------------------
657
+ // Debrief Extraction
658
+ // ---------------------------------------------------------------------------
659
+ /**
660
+ * Canonical debrief system prompt — must be identical across all clients.
661
+ */
662
+ exports.DEBRIEF_SYSTEM_PROMPT = `You are reviewing a conversation that just ended. The following facts were
663
+ already extracted and stored during this conversation:
664
+
665
+ {already_stored_facts}
666
+
667
+ Your job is to capture what turn-by-turn extraction MISSED. Focus on:
668
+
669
+ 1. **Broader context** — What was the conversation about overall? What project,
670
+ problem, or topic tied the discussion together?
671
+ 2. **Outcomes & conclusions** — What was decided, agreed upon, or resolved?
672
+ 3. **What was attempted** — What approaches were tried? What worked, what didn't, and why?
673
+ 4. **Relationships** — How do topics discussed relate to each other or to things
674
+ from previous conversations?
675
+ 5. **Open threads** — What was left unfinished or needs follow-up?
676
+
677
+ Do NOT repeat facts already stored. Only add genuinely new information that provides
678
+ broader context a future conversation would benefit from.
679
+
680
+ Return a JSON array (no markdown, no code fences):
681
+ [{"text": "...", "type": "summary|context", "importance": N}]
682
+
683
+ - Use type "summary" for conclusions, outcomes, and decisions-of-the-session
684
+ - Use type "context" for broader project context, open threads, and what-was-tried
685
+ - Importance 7-8 for most debrief items (they are high-value by definition)
686
+ - Maximum 5 items (debriefs should be concise, not exhaustive)
687
+ - Each item should be 1-3 sentences, self-contained
688
+
689
+ If the conversation was too short or trivial to warrant a debrief, return: []`;
690
+ /**
691
+ * Parse a debrief response into validated DebriefItems.
692
+ */
693
+ function parseDebriefResponse(response) {
694
+ let cleaned = response.trim();
695
+ if (cleaned.startsWith('```')) {
696
+ cleaned = cleaned.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();
697
+ }
698
+ try {
699
+ const parsed = JSON.parse(cleaned);
700
+ if (!Array.isArray(parsed))
701
+ return [];
702
+ return parsed
703
+ .filter((item) => item &&
704
+ typeof item === 'object' &&
705
+ typeof item.text === 'string' &&
706
+ item.text.length >= 5)
707
+ .map((item) => {
708
+ const d = item;
709
+ const type = d.type === 'summary' ? 'summary' : 'context';
710
+ const rawImportance = typeof d.importance === 'number' ? d.importance : 7;
711
+ const importance = Math.max(1, Math.min(10, rawImportance));
712
+ return { text: String(d.text).slice(0, 512), type, importance };
713
+ })
714
+ .filter((d) => d.importance >= 6)
715
+ .slice(0, 5);
716
+ }
717
+ catch {
718
+ return [];
719
+ }
720
+ }
721
+ /**
722
+ * Extract a session debrief using LLM.
723
+ *
724
+ * @param rawMessages - All messages from the session
725
+ * @param storedFactTexts - Texts of facts already stored in this session (for dedup)
726
+ * @returns Array of debrief items, or empty array on failure
727
+ */
728
+ async function extractDebrief(rawMessages, storedFactTexts) {
729
+ const config = (0, llm_client_js_1.resolveLLMConfig)();
730
+ if (!config)
731
+ return [];
732
+ const parsed = rawMessages
733
+ .map(messageToText)
734
+ .filter((m) => m !== null);
735
+ // Minimum 4 turns (8 messages) to warrant a debrief
736
+ if (parsed.length < 8)
737
+ return [];
738
+ const conversationText = truncateMessages(parsed, 12_000);
739
+ if (conversationText.length < 20)
740
+ return [];
741
+ const alreadyStored = storedFactTexts.length > 0
742
+ ? storedFactTexts.map((t) => `- ${t}`).join('\n')
743
+ : '(none)';
744
+ const systemPrompt = exports.DEBRIEF_SYSTEM_PROMPT.replace('{already_stored_facts}', alreadyStored);
745
+ try {
746
+ const response = await (0, llm_client_js_1.chatCompletion)(config, [
747
+ { role: 'system', content: systemPrompt },
748
+ { role: 'user', content: `Review this conversation and provide a debrief:\n\n${conversationText}` },
749
+ ], {
750
+ // 3.3.1-rc.2: retry transient 429 / timeout.
751
+ retry: { attempts: 3, baseDelayMs: 1000 },
752
+ timeoutMs: 30_000,
753
+ });
754
+ if (!response)
755
+ return [];
756
+ return parseDebriefResponse(response);
757
+ }
758
+ catch {
759
+ return [];
760
+ }
761
+ }
762
+ // ---------------------------------------------------------------------------
763
+ // v1 Taxonomy Extraction Pipeline (default as of plugin v3.0.0)
764
+ //
765
+ // Produces facts conforming to Memory Taxonomy v1 (6 types: claim,
766
+ // preference, directive, commitment, episode, summary; 5 sources; 8 scopes).
767
+ //
768
+ // The G-pipeline uses a single merged-topic prompt that returns both the
769
+ // 2-3 main topics the user engaged with AND the extracted facts, so topic
770
+ // anchoring is preserved within one call. After extraction we apply:
771
+ //
772
+ // 1. `applyProvenanceFilterLax` — tag-don't-drop. Assistant-sourced facts
773
+ // get their importance capped at 7 rather than being filtered out; the
774
+ // reranker later uses the source field to deprioritize them.
775
+ // 2. `comparativeRescoreV1` — spread importance across the 1-10 range
776
+ // and assign volatility. Forced when the batch has >= 5 facts.
777
+ // 3. `defaultVolatility` — heuristic fallback.
778
+ //
779
+ // This matches the winning G pipeline from the 200-conv benchmark.
780
+ // ---------------------------------------------------------------------------
781
+ /**
782
+ * The main extraction system prompt (v1 merged-topic pipeline).
783
+ *
784
+ * Exported as both `EXTRACTION_SYSTEM_PROMPT` (canonical) and
785
+ * `EXTRACTION_SYSTEM_PROMPT_V1_MERGED` (deprecated alias) for back-compat.
786
+ */
787
+ exports.EXTRACTION_SYSTEM_PROMPT = `You are a memory extraction engine using Memory Taxonomy v1. Work in TWO explicit phases within one response:
788
+
789
+ PHASE 1 — Topic identification.
790
+ Before extracting any fact, identify the 2-3 main topics the user was engaging with. Topics should be short phrases (2-5 words each). If the conversation has no clear user-focused topic, use an empty topics array.
791
+
792
+ PHASE 2 — Fact extraction anchored to those topics.
793
+ Extract valuable memories. Prefer facts that directly relate to the identified topics (importance 7-9 range). Tangential facts may still be extracted but score lower (6-7 range).
794
+
795
+ Rules:
796
+ 1. Each memory = single self-contained piece of information
797
+ 2. Focus on user-specific info useful in future conversations
798
+ 3. Skip generic knowledge, greetings, small talk, ephemeral task coordination
799
+ 4. Score importance 1-10 (6+ = worth storing)
800
+ 5. Every memory MUST attribute a source (provenance critical)
801
+
802
+ Importance rubric (use FULL 1-10 range):
803
+ - 10: Critical, core identity, never-forget content
804
+ - 9: Affects many future decisions
805
+ - 8: High-value preference/decision/rule
806
+ - 7: Specific durable fact
807
+ - 6: Borderline
808
+ - 5 or below: NOT worth storing — drop
809
+
810
+ DO NOT cluster everything at 7-8-9.
811
+
812
+ ═══════════════════════════════════════════════════════════════
813
+ TYPE (6 values)
814
+ ═══════════════════════════════════════════════════════════════
815
+ - claim: factual assertion (absorbs fact/context/decision; decisions populate reasoning field)
816
+ - preference: likes/dislikes/tastes
817
+ - directive: imperative rule ("always X", "never Y")
818
+ - commitment: future intent ("will do X")
819
+ - episode: notable event
820
+ - summary: derived synthesis (source must be derived|assistant) — do NOT emit for turn-extraction
821
+
822
+ ═══════════════════════════════════════════════════════════════
823
+ SOURCE (provenance, CRITICAL)
824
+ ═══════════════════════════════════════════════════════════════
825
+ - user: user explicitly stated it (in [user]: turns)
826
+ - user-inferred: extractor inferred from user signals
827
+ - assistant: assistant authored content — DOWNGRADE unless user affirmed/quoted/used it
828
+ - external, derived: rare
829
+
830
+ IF fact substance appears ONLY in [assistant]: turns without user affirmation → source:assistant
831
+
832
+ ═══════════════════════════════════════════════════════════════
833
+ SCOPE (life domain)
834
+ ═══════════════════════════════════════════════════════════════
835
+ work | personal | health | family | creative | finance | misc | unspecified
836
+
837
+ ═══════════════════════════════════════════════════════════════
838
+ ENTITIES
839
+ ═══════════════════════════════════════════════════════════════
840
+ - type ∈ {person, project, tool, company, concept, place}
841
+ - prefer specific names ("PostgreSQL" not "database")
842
+ - omit umbrella categories when specific name is present
843
+
844
+ ═══════════════════════════════════════════════════════════════
845
+ REASONING (only for claims that are decisions)
846
+ ═══════════════════════════════════════════════════════════════
847
+ For type=claim where the user expressed a decision-with-reasoning, populate "reasoning" with the WHY clause.
848
+
849
+ ═══════════════════════════════════════════════════════════════
850
+ OUTPUT FORMAT (no markdown, no code fences)
851
+ ═══════════════════════════════════════════════════════════════
852
+ {
853
+ "topics": ["topic 1", "topic 2"],
854
+ "facts": [
855
+ {
856
+ "text": "...",
857
+ "type": "claim|preference|directive|commitment|episode",
858
+ "source": "user|user-inferred|assistant",
859
+ "scope": "work|personal|health|...",
860
+ "importance": N,
861
+ "confidence": 0.9,
862
+ "action": "ADD",
863
+ "reasoning": "...", // optional, only for claim+decision
864
+ "entities": [{"name": "...", "type": "tool"}]
865
+ }
866
+ ]
867
+ }
868
+
869
+ If nothing worth extracting: {"topics": [], "facts": []}`;
870
+ /**
871
+ * @deprecated Use `EXTRACTION_SYSTEM_PROMPT` instead. Kept only as a
872
+ * back-compat alias for callers that imported the v1 rollout name.
873
+ */
874
+ exports.EXTRACTION_SYSTEM_PROMPT_V1_MERGED = exports.EXTRACTION_SYSTEM_PROMPT;
875
+ /**
876
+ * Parse a v1 merged-topic LLM response. Returns both the topic list and the
877
+ * validated/filtered fact list. Illegal combinations (summary+user) are
878
+ * dropped; importance < 6 with action != DELETE is dropped.
879
+ *
880
+ * Exported as both `parseFactsResponse` (canonical, returns facts array) and
881
+ * `parseMergedResponseV1` (returns `{ topics, facts }`). Prefer the former
882
+ * unless the topic list is needed.
883
+ */
884
+ function parseMergedResponseV1(response, logger) {
885
+ const originalPreview = response.trim().slice(0, 200);
886
+ let cleaned = response.trim();
887
+ cleaned = cleaned.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '').trim();
888
+ if (cleaned.startsWith('```')) {
889
+ cleaned = cleaned.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();
890
+ }
891
+ const tryParse = (input) => {
892
+ try {
893
+ return JSON.parse(input);
894
+ }
895
+ catch {
896
+ return undefined;
897
+ }
898
+ };
899
+ let parsed = tryParse(cleaned);
900
+ let recoveryUsed = 'none';
901
+ if (parsed === undefined) {
902
+ // First try an outermost-array greedy match (legacy bare-array format).
903
+ const arrMatch = cleaned.match(/\[[\s\S]*\]/);
904
+ if (arrMatch) {
905
+ parsed = tryParse(arrMatch[0]);
906
+ if (parsed !== undefined)
907
+ recoveryUsed = 'bracket-scan';
908
+ }
909
+ if (parsed === undefined) {
910
+ // Fall back to an outermost-object greedy match (merged-topic format).
911
+ const objMatch = cleaned.match(/\{[\s\S]*\}/);
912
+ if (objMatch) {
913
+ parsed = tryParse(objMatch[0]);
914
+ if (parsed !== undefined)
915
+ recoveryUsed = 'bracket-scan';
916
+ }
917
+ }
918
+ }
919
+ if (recoveryUsed === 'bracket-scan') {
920
+ logger?.info?.(`parseFactsResponse: recovered JSON via bracket-scan fallback`);
921
+ }
922
+ if (!parsed || typeof parsed !== 'object') {
923
+ logger?.warn?.(`parseFactsResponse: could not parse LLM output as JSON. Preview: ${JSON.stringify(originalPreview)}`);
924
+ return { topics: [], facts: [] };
925
+ }
926
+ // Dual-format acceptance: either the merged object `{ topics, facts }` or
927
+ // a bare JSON array of fact objects (legacy / test fixture shape). The
928
+ // bare array is wrapped as { topics: [], facts: [...] } so the downstream
929
+ // logic stays uniform. A single fact object (no wrapper) is also wrapped.
930
+ let obj;
931
+ if (Array.isArray(parsed)) {
932
+ obj = { topics: [], facts: parsed };
933
+ }
934
+ else if (typeof parsed.facts === 'undefined' &&
935
+ typeof parsed.text === 'string') {
936
+ // Single fact object, not a merged wrapper.
937
+ obj = { topics: [], facts: [parsed] };
938
+ }
939
+ else {
940
+ obj = parsed;
941
+ }
942
+ const rawTopics = obj.topics;
943
+ const topics = Array.isArray(rawTopics)
944
+ ? rawTopics
945
+ .filter((t) => typeof t === 'string' && t.length > 0)
946
+ .slice(0, 3)
947
+ : [];
948
+ const rawFacts = obj.facts;
949
+ if (!Array.isArray(rawFacts))
950
+ return { topics, facts: [] };
951
+ const validActions = ['ADD', 'UPDATE', 'DELETE', 'NOOP'];
952
+ const facts = rawFacts
953
+ .filter((f) => !!f &&
954
+ typeof f === 'object' &&
955
+ typeof f.text === 'string' &&
956
+ f.text.length >= 5)
957
+ .map((f) => {
958
+ const rawType = String(f.type ?? 'claim').toLowerCase();
959
+ // Accept both v1 tokens and legacy v0 tokens — coerce v0 via V0_TO_V1_TYPE.
960
+ let type;
961
+ if (isValidMemoryType(rawType)) {
962
+ type = rawType;
963
+ }
964
+ else if (exports.LEGACY_V0_MEMORY_TYPES.includes(rawType)) {
965
+ type = exports.V0_TO_V1_TYPE[rawType];
966
+ }
967
+ else {
968
+ type = 'claim';
969
+ }
970
+ const rawSource = String(f.source ?? 'user-inferred').toLowerCase();
971
+ const source = exports.VALID_MEMORY_SOURCES.includes(rawSource)
972
+ ? rawSource
973
+ : 'user-inferred';
974
+ const rawScope = String(f.scope ?? 'unspecified').toLowerCase();
975
+ const scope = exports.VALID_MEMORY_SCOPES.includes(rawScope)
976
+ ? rawScope
977
+ : 'unspecified';
978
+ const reasoning = typeof f.reasoning === 'string' ? f.reasoning.slice(0, 256) : undefined;
979
+ const action = validActions.includes(String(f.action))
980
+ ? String(f.action)
981
+ : 'ADD';
982
+ let entities;
983
+ if (Array.isArray(f.entities)) {
984
+ const valid = f.entities
985
+ .map(parseEntity)
986
+ .filter((e) => e !== null);
987
+ if (valid.length > 0)
988
+ entities = valid;
989
+ }
990
+ const fact = {
991
+ text: String(f.text).slice(0, 512),
992
+ type,
993
+ source,
994
+ scope,
995
+ reasoning,
996
+ importance: Math.max(1, Math.min(10, Number(f.importance) || 5)),
997
+ confidence: normalizeConfidence(f.confidence),
998
+ action,
999
+ existingFactId: typeof f.existingFactId === 'string' ? f.existingFactId : undefined,
1000
+ };
1001
+ if (entities)
1002
+ fact.entities = entities;
1003
+ return fact;
1004
+ })
1005
+ // Reject illegal type:summary + source:user
1006
+ .filter((f) => !(f.type === 'summary' && f.source === 'user'))
1007
+ // Importance threshold (preserves DELETE)
1008
+ .filter((f) => f.importance >= 6 || f.action === 'DELETE');
1009
+ return { topics, facts };
1010
+ }
1011
+ /**
1012
+ * Parse an LLM extraction response into structured v1 facts. Canonical
1013
+ * parser used by the default `extractFacts()` pipeline.
1014
+ *
1015
+ * This is a thin wrapper around `parseMergedResponseV1` that discards the
1016
+ * topic list so existing callers that expect a flat `ExtractedFact[]`
1017
+ * signature keep working.
1018
+ */
1019
+ function parseFactsResponse(response, logger) {
1020
+ return parseMergedResponseV1(response, logger).facts;
1021
+ }
1022
+ /**
1023
+ * Tag-don't-drop provenance filter (pipeline G / F).
1024
+ *
1025
+ * For each fact:
1026
+ * - If source is already "assistant", cap importance at 7.
1027
+ * - Otherwise, keyword-match the fact against user turns. If <30% of
1028
+ * content words (length >= 4) appear in user turns AND source != "user",
1029
+ * tag source as "assistant" and cap importance at 7 (keep the fact).
1030
+ * - Drop facts below importance 5 (unless DELETE action).
1031
+ */
1032
+ function applyProvenanceFilterLax(facts, conversationText) {
1033
+ const userTurnsLower = conversationText
1034
+ .split(/\n\n/)
1035
+ .filter((line) => line.startsWith('[user]:'))
1036
+ .join(' ')
1037
+ .toLowerCase();
1038
+ return facts
1039
+ .map((f) => {
1040
+ if (f.source === 'assistant') {
1041
+ return { ...f, importance: Math.min(f.importance, 7) };
1042
+ }
1043
+ const factWords = f.text
1044
+ .toLowerCase()
1045
+ .replace(/[^a-z0-9\s]/g, ' ')
1046
+ .split(/\s+/)
1047
+ .filter((w) => w.length >= 4);
1048
+ const matchedWords = factWords.filter((w) => userTurnsLower.includes(w)).length;
1049
+ const matchRatio = factWords.length > 0 ? matchedWords / factWords.length : 0;
1050
+ if (matchRatio < 0.3 && f.source !== 'user') {
1051
+ return {
1052
+ ...f,
1053
+ source: 'assistant',
1054
+ importance: Math.min(f.importance, 7),
1055
+ };
1056
+ }
1057
+ return f;
1058
+ })
1059
+ .filter((f) => f.importance >= 5 || f.action === 'DELETE');
1060
+ }
1061
+ /**
1062
+ * Heuristic fallback volatility when the LLM doesn't assign one.
1063
+ */
1064
+ function defaultVolatility(f) {
1065
+ if (f.type === 'commitment')
1066
+ return 'updatable';
1067
+ if (f.type === 'episode')
1068
+ return 'stable';
1069
+ if (f.type === 'directive')
1070
+ return 'stable';
1071
+ if (f.scope === 'health' || f.scope === 'family')
1072
+ return 'stable';
1073
+ return 'updatable';
1074
+ }
1075
+ const COMPARATIVE_PROMPT_V1 = `You are a memory re-ranker for the v1 taxonomy. You receive facts already extracted from one conversation, each with initial importance. Your job is twofold:
1076
+
1077
+ 1. RE-RANK importance to spread across the 1-10 range (avoid clustering at 7-8-9)
1078
+ 2. ASSIGN volatility to each fact
1079
+
1080
+ Re-ranking rules:
1081
+ - Top 1/3 of facts (most significant for this user): importance 9-10
1082
+ - Middle 1/3: importance 7-8
1083
+ - Bottom 1/3: importance 5-6 (borderline, may be dropped)
1084
+ - A fact may stay at 10 if it's clearly identity-defining (name, birthday) or marked as "never forget"
1085
+ - Never raise without justification; never lower below 5 unless clearly noise
1086
+ - You MUST produce a spread
1087
+
1088
+ Volatility rules:
1089
+ - stable: unlikely to change for years (name, allergies, birthplace, fundamental traits)
1090
+ - updatable: changes occasionally (current job, active project, partner's name, address)
1091
+ - ephemeral: short-lived state (today's task, this week's plan, current trip itinerary)
1092
+
1093
+ Use the FULL conversation context to judge volatility — a single claim may be ambiguous, but in context you can usually tell.
1094
+
1095
+ Return JSON array, same order as input, ONLY with importance + volatility fields:
1096
+ [{"importance": N, "volatility": "stable|updatable|ephemeral"}, ...]
1097
+ No markdown.`;
1098
+ /**
1099
+ * Comparative re-scoring pass (v1). Forces re-scoring when facts.length >= 5
1100
+ * so the importance distribution spreads across the 1-10 range. When
1101
+ * facts.length < 5, assigns defaultVolatility and returns.
1102
+ */
1103
+ async function comparativeRescoreV1(facts, conversationText, logger) {
1104
+ // G-tuned behavior: force rescore when >= 5 facts
1105
+ if (facts.length < 2 || facts.length < 5) {
1106
+ return facts.map((f) => ({ ...f, volatility: f.volatility ?? defaultVolatility(f) }));
1107
+ }
1108
+ const config = (0, llm_client_js_1.resolveLLMConfig)();
1109
+ if (!config) {
1110
+ return facts.map((f) => ({ ...f, volatility: defaultVolatility(f) }));
1111
+ }
1112
+ const factsForPrompt = facts
1113
+ .map((f, i) => `${i + 1}. [imp: ${f.importance}] [type: ${f.type}] [scope: ${f.scope ?? 'unspecified'}] ${f.text}`)
1114
+ .join('\n');
1115
+ const userPrompt = `Conversation context:\n${conversationText}\n\nExtracted facts:\n${factsForPrompt}\n\nReturn ${facts.length} JSON objects, each with "importance" + "volatility". Match input order.`;
1116
+ let response;
1117
+ try {
1118
+ response = await (0, llm_client_js_1.chatCompletion)(config, [
1119
+ { role: 'system', content: COMPARATIVE_PROMPT_V1 },
1120
+ { role: 'user', content: userPrompt },
1121
+ ], {
1122
+ // 3.3.1-rc.2: retry transient 429 / timeout (rescore is an inner
1123
+ // call after extractFacts — if extraction backs off successfully
1124
+ // the rescore usually also passes on first try, but keep symmetry).
1125
+ retry: { attempts: 3, baseDelayMs: 1000 },
1126
+ timeoutMs: 30_000,
1127
+ logger,
1128
+ });
1129
+ }
1130
+ catch (err) {
1131
+ const msg = err instanceof Error ? err.message : String(err);
1132
+ logger?.warn?.(`comparativeRescoreV1: chatCompletion threw: ${msg}`);
1133
+ return facts.map((f) => ({ ...f, volatility: defaultVolatility(f) }));
1134
+ }
1135
+ if (!response) {
1136
+ return facts.map((f) => ({ ...f, volatility: defaultVolatility(f) }));
1137
+ }
1138
+ let cleaned = response.trim();
1139
+ cleaned = cleaned.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '').trim();
1140
+ if (cleaned.startsWith('```')) {
1141
+ cleaned = cleaned.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();
1142
+ }
1143
+ const match = cleaned.match(/\[[\s\S]*\]/);
1144
+ if (match)
1145
+ cleaned = match[0];
1146
+ let parsed;
1147
+ try {
1148
+ parsed = JSON.parse(cleaned);
1149
+ }
1150
+ catch {
1151
+ return facts.map((f) => ({ ...f, volatility: defaultVolatility(f) }));
1152
+ }
1153
+ if (!Array.isArray(parsed)) {
1154
+ return facts.map((f) => ({ ...f, volatility: defaultVolatility(f) }));
1155
+ }
1156
+ return facts.map((f, i) => {
1157
+ const entry = parsed[i];
1158
+ const rawImp = entry && typeof entry === 'object' ? Number(entry.importance) : NaN;
1159
+ const rawVol = entry && typeof entry === 'object' ? String(entry.volatility ?? '').toLowerCase() : '';
1160
+ const newImp = Number.isFinite(rawImp)
1161
+ ? Math.max(5, Math.min(10, Math.round(rawImp)))
1162
+ : f.importance;
1163
+ const newVol = exports.VALID_MEMORY_VOLATILITIES.includes(rawVol)
1164
+ ? rawVol
1165
+ : defaultVolatility(f);
1166
+ return { ...f, importance: newImp, volatility: newVol };
1167
+ });
1168
+ }
1169
+ /**
1170
+ * Main extraction entry point (default pipeline as of plugin v3.0.0).
1171
+ *
1172
+ * Pipeline: single merged-topic LLM call → `applyProvenanceFilterLax`
1173
+ * (tag-don't-drop) → `comparativeRescoreV1` (forces re-rank when >= 5 facts)
1174
+ * → `defaultVolatility` fallback → lexical importance bumps.
1175
+ *
1176
+ * Produces v1-shaped facts with `type`, `source`, `scope`, `volatility`,
1177
+ * and optional `reasoning` fields populated. The caller should hand the
1178
+ * result to `storeExtractedFacts` which emits a v1 canonical claim blob.
1179
+ */
1180
+ async function extractFacts(rawMessages, mode, existingMemories, profileContext, logger) {
1181
+ const config = (0, llm_client_js_1.resolveLLMConfig)();
1182
+ if (!config) {
1183
+ logger?.info?.('extractFacts: no LLM config resolved (skipping extraction)');
1184
+ return [];
1185
+ }
1186
+ const parsed = rawMessages
1187
+ .map(messageToText)
1188
+ .filter((m) => m !== null);
1189
+ if (parsed.length === 0) {
1190
+ logger?.info?.(`extractFacts: no parseable messages (raw count=${rawMessages.length})`);
1191
+ return [];
1192
+ }
1193
+ const relevantMessages = mode === 'turn' ? parsed.slice(-6) : parsed;
1194
+ const conversationText = truncateMessages(relevantMessages, 12_000);
1195
+ if (conversationText.length < 20) {
1196
+ logger?.info?.(`extractFacts: conversation too short (${conversationText.length} chars < 20, parsed=${parsed.length}, mode=${mode})`);
1197
+ return [];
1198
+ }
1199
+ let memoriesContext = '';
1200
+ if (existingMemories && existingMemories.length > 0) {
1201
+ const memoriesStr = existingMemories
1202
+ .map((m) => `[ID: ${m.id}] ${m.text}`)
1203
+ .join('\n');
1204
+ memoriesContext = `\n\nExisting memories (use these for dedup — classify as UPDATE/DELETE/NOOP if they conflict or overlap):\n${memoriesStr}`;
1205
+ }
1206
+ const userPrompt = mode === 'turn'
1207
+ ? `Extract important facts from these recent conversation turns:\n\n${conversationText}${memoriesContext}`
1208
+ : `Extract ALL valuable long-term memories from this conversation before it is lost:\n\n${conversationText}${memoriesContext}`;
1209
+ const systemPrompt = profileContext || exports.EXTRACTION_SYSTEM_PROMPT;
1210
+ let response;
1211
+ try {
1212
+ response = await (0, llm_client_js_1.chatCompletion)(config, [
1213
+ { role: 'system', content: systemPrompt },
1214
+ { role: 'user', content: userPrompt },
1215
+ ], {
1216
+ // 3.3.1-rc.2: the headline fix for the rc.1 QA NO-GO — 5/6 extraction
1217
+ // windows failed on zai 429 + timeouts with no retry. 3 attempts with
1218
+ // 1s → 2s → 4s backoff recovers virtually all transient rate-limit
1219
+ // hiccups. Graceful timeout: per-attempt 30s, total worst-case 30+1+30+2+30+4≈97s.
1220
+ retry: { attempts: 3, baseDelayMs: 1000 },
1221
+ timeoutMs: 30_000,
1222
+ logger,
1223
+ });
1224
+ }
1225
+ catch (err) {
1226
+ const msg = err instanceof Error ? err.message : String(err);
1227
+ logger?.warn?.(`extractFacts: chatCompletion threw: ${msg}`);
1228
+ return [];
1229
+ }
1230
+ if (!response) {
1231
+ logger?.info?.('extractFacts: chatCompletion returned null/empty response');
1232
+ return [];
1233
+ }
1234
+ logger?.info?.(`extractFacts: LLM returned ${response.length} chars; parsing merged response`);
1235
+ const { topics, facts: rawFacts } = parseMergedResponseV1(response, logger);
1236
+ if (topics.length > 0) {
1237
+ logger?.info?.(`extractFacts: topics = ${JSON.stringify(topics)}`);
1238
+ }
1239
+ // Provenance filter (tag-don't-drop)
1240
+ let facts = applyProvenanceFilterLax(rawFacts, conversationText);
1241
+ // Comparative rescore (forces re-rank when >= 5 facts)
1242
+ facts = await comparativeRescoreV1(facts, conversationText, logger);
1243
+ // Ensure every fact has a volatility (defensive: rescore may have skipped)
1244
+ facts = facts.map((f) => ({ ...f, volatility: f.volatility ?? defaultVolatility(f) }));
1245
+ // Lexical importance bumps (same as v0 pipeline)
1246
+ for (const f of facts) {
1247
+ const bump = computeLexicalImportanceBump(f.text, conversationText);
1248
+ if (bump > 0) {
1249
+ const oldImportance = f.importance;
1250
+ const effectiveBump = f.importance >= 8 ? Math.min(bump, 1) : bump;
1251
+ f.importance = Math.min(10, f.importance + effectiveBump);
1252
+ logger?.info?.(`extractFacts: lexical bump +${bump} for "${f.text.slice(0, 60)}..." (${oldImportance} → ${f.importance})`);
1253
+ }
1254
+ }
1255
+ return facts;
1256
+ }
1257
+ //# sourceMappingURL=extractor.js.map