@byte5ai/palaia 1.8.1 → 2.0.2

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.
package/src/hooks.ts CHANGED
@@ -1,14 +1,588 @@
1
1
  /**
2
2
  * Lifecycle hooks for the Palaia OpenClaw plugin.
3
3
  *
4
- * - before_prompt_build: Injects HOT memory into agent context (opt-in).
4
+ * - before_prompt_build: Query-based contextual recall (Issue #65).
5
+ * Returns appendSystemContext with 🧠 instruction when memory is used.
6
+ * - agent_end: Auto-capture of significant exchanges (Issue #64).
7
+ * Now with LLM-based extraction via OpenClaw's runEmbeddedPiAgent,
8
+ * falling back to rule-based extraction if the LLM is unavailable.
9
+ * - message_received: Captures inbound message ID for emoji reactions.
5
10
  * - palaia-recovery service: Replays WAL on startup.
11
+ * - /palaia command: Show memory status.
6
12
  */
7
13
 
8
- import { runJson, recover, type RunnerOpts } from "./runner.js";
9
- import type { PalaiaPluginConfig } from "./config.js";
14
+ import fs from "node:fs/promises";
15
+ import path from "node:path";
16
+ import os from "node:os";
17
+ import { run, runJson, recover, type RunnerOpts } from "./runner.js";
18
+ import type { PalaiaPluginConfig, RecallTypeWeights } from "./config.js";
10
19
 
11
- /** Shape returned by `palaia query --json` */
20
+ // ============================================================================
21
+ // Plugin State Persistence (Issue #87: Recall counter for nudges)
22
+ // ============================================================================
23
+
24
+ interface PluginState {
25
+ successfulRecalls: number;
26
+ satisfactionNudged: boolean;
27
+ transparencyNudged: boolean;
28
+ firstRecallTimestamp: string | null;
29
+ }
30
+
31
+ const DEFAULT_PLUGIN_STATE: PluginState = {
32
+ successfulRecalls: 0,
33
+ satisfactionNudged: false,
34
+ transparencyNudged: false,
35
+ firstRecallTimestamp: null,
36
+ };
37
+
38
+ /**
39
+ * Load plugin state from disk.
40
+ *
41
+ * Note: No file locking is applied here. The plugin-state.json file stores
42
+ * non-critical counters (recall count, nudge flags). In the worst case of a
43
+ * race condition between multiple agents, a nudge fires one recall too early
44
+ * or too late. This is acceptable given the low-stakes nature of the data
45
+ * and the complexity cost of adding advisory locks in Node.js.
46
+ */
47
+ async function loadPluginState(workspace?: string): Promise<PluginState> {
48
+ const dir = workspace || process.cwd();
49
+ const statePath = path.join(dir, ".palaia", "plugin-state.json");
50
+ try {
51
+ const raw = await fs.readFile(statePath, "utf-8");
52
+ return { ...DEFAULT_PLUGIN_STATE, ...JSON.parse(raw) };
53
+ } catch {
54
+ return { ...DEFAULT_PLUGIN_STATE };
55
+ }
56
+ }
57
+
58
+ async function savePluginState(state: PluginState, workspace?: string): Promise<void> {
59
+ const dir = workspace || process.cwd();
60
+ const statePath = path.join(dir, ".palaia", "plugin-state.json");
61
+ try {
62
+ await fs.writeFile(statePath, JSON.stringify(state, null, 2));
63
+ } catch {
64
+ // Non-fatal
65
+ }
66
+ }
67
+
68
+ // ============================================================================
69
+ // Session-isolated Turn State (Issue #87: Emoji Reactions)
70
+ // ============================================================================
71
+
72
+ /** Per-session turn state for tracking recall/capture across hooks. */
73
+ interface TurnState {
74
+ recallOccurred: boolean;
75
+ lastInboundMessageId: string | null;
76
+ lastInboundChannelId: string | null;
77
+ channelProvider: string | null;
78
+ capturedInThisTurn: boolean;
79
+ /** Timestamp when this entry was created (for TTL-based pruning). */
80
+ createdAt: number;
81
+ }
82
+
83
+ function createDefaultTurnState(): TurnState {
84
+ return {
85
+ recallOccurred: false,
86
+ lastInboundMessageId: null,
87
+ lastInboundChannelId: null,
88
+ channelProvider: null,
89
+ capturedInThisTurn: false,
90
+ createdAt: Date.now(),
91
+ };
92
+ }
93
+
94
+ /** Maximum age for turn state entries before they are pruned (5 minutes). */
95
+ const TURN_STATE_TTL_MS = 5 * 60 * 1000;
96
+ /** Maximum age for inbound message entries before they are pruned (5 minutes). */
97
+ const INBOUND_MESSAGE_TTL_MS = 5 * 60 * 1000;
98
+
99
+ /**
100
+ * Remove stale entries from turnStateBySession and lastInboundMessageByChannel.
101
+ * Called at the start of before_prompt_build to prevent memory leaks from
102
+ * sessions that were killed/crashed without firing agent_end.
103
+ */
104
+ export function pruneStaleEntries(): void {
105
+ const now = Date.now();
106
+ for (const [key, state] of turnStateBySession) {
107
+ if (now - state.createdAt > TURN_STATE_TTL_MS) {
108
+ turnStateBySession.delete(key);
109
+ }
110
+ }
111
+ for (const [key, entry] of lastInboundMessageByChannel) {
112
+ if (now - entry.timestamp > INBOUND_MESSAGE_TTL_MS) {
113
+ lastInboundMessageByChannel.delete(key);
114
+ }
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Session-isolated turn state map. Keyed by sessionKey.
120
+ * Set in before_prompt_build / message_received, consumed + deleted in agent_end.
121
+ * NEVER use global variables for turn data — race condition with multi-agent.
122
+ */
123
+ const turnStateBySession = new Map<string, TurnState>();
124
+
125
+ // ============================================================================
126
+ // Inbound Message ID Store (for emoji reactions)
127
+ // ============================================================================
128
+
129
+ /**
130
+ * Stores the most recent inbound message ID per channel.
131
+ * Keyed by channelId (e.g. "C0AKE2G15HV"), value is the message ts.
132
+ * Written by message_received, consumed by agent_end.
133
+ * Entries are short-lived and cleaned up after agent_end.
134
+ */
135
+ const lastInboundMessageByChannel = new Map<string, { messageId: string; provider: string; timestamp: number }>();
136
+
137
+ /** Channels that support emoji reactions. */
138
+ const REACTION_SUPPORTED_PROVIDERS = new Set(["slack", "discord"]);
139
+
140
+ // ============================================================================
141
+ // Scope Validation (Issue #90)
142
+ // ============================================================================
143
+
144
+ const VALID_SCOPES = ["private", "team", "public"];
145
+
146
+ /**
147
+ * Check if a scope string is valid for palaia write.
148
+ * Valid: "private", "team", "public", or any "shared:*" prefix.
149
+ */
150
+ export function isValidScope(s: string): boolean {
151
+ return VALID_SCOPES.includes(s) || s.startsWith("shared:");
152
+ }
153
+
154
+ /**
155
+ * Sanitize a scope value — returns the value if valid, otherwise fallback.
156
+ */
157
+ export function sanitizeScope(rawScope: string | null | undefined, fallback = "team"): string {
158
+ if (rawScope && isValidScope(rawScope)) return rawScope;
159
+ return fallback;
160
+ }
161
+
162
+ // ============================================================================
163
+ // Session Key Helpers
164
+ // ============================================================================
165
+
166
+ /**
167
+ * Extract channel target from a session key.
168
+ * e.g. "agent:main:slack:channel:c0ake2g15hv" → "channel:C0AKE2G15HV"
169
+ */
170
+ export function extractTargetFromSessionKey(sessionKey: string): string | undefined {
171
+ const parts = sessionKey.split(":");
172
+ for (let i = 0; i < parts.length - 1; i++) {
173
+ if (parts[i] === "channel" || parts[i] === "dm" || parts[i] === "group") {
174
+ return `${parts[i]}:${parts[i + 1].toUpperCase()}`;
175
+ }
176
+ }
177
+ return undefined;
178
+ }
179
+
180
+ /**
181
+ * Extract channel provider from a session key.
182
+ * e.g. "agent:main:slack:channel:c0ake2g15hv" → "slack"
183
+ */
184
+ export function extractChannelFromSessionKey(sessionKey: string): string | undefined {
185
+ const parts = sessionKey.split(":");
186
+ if (parts.length >= 5 && parts[0] === "agent") {
187
+ return parts[2];
188
+ }
189
+ return undefined;
190
+ }
191
+
192
+ // ============================================================================
193
+ // Emoji Reaction Helpers (Issue #87: Reactions)
194
+ // ============================================================================
195
+
196
+ /**
197
+ * Extract the Slack channel ID from a session key.
198
+ * e.g. "agent:main:slack:channel:c0ake2g15hv" → "C0AKE2G15HV"
199
+ */
200
+ export function extractSlackChannelIdFromSessionKey(sessionKey: string): string | undefined {
201
+ const parts = sessionKey.split(":");
202
+ for (let i = 0; i < parts.length - 1; i++) {
203
+ if (parts[i] === "channel" || parts[i] === "dm") {
204
+ return parts[i + 1].toUpperCase();
205
+ }
206
+ }
207
+ return undefined;
208
+ }
209
+
210
+ /**
211
+ * Extract the real Slack channel ID from event metadata or ctx.
212
+ * OpenClaw stores the channel in "channel:C0AKE2G15HV" format in:
213
+ * - event.metadata.to
214
+ * - event.metadata.originatingTo
215
+ * - ctx.conversationId
216
+ *
217
+ * ctx.channelId is the PROVIDER NAME ("slack"), not the channel ID.
218
+ * ctx.sessionKey is null during message_received.
219
+ */
220
+ export function extractChannelIdFromEvent(event: any, ctx: any): string | undefined {
221
+ const rawTo = event?.metadata?.to
222
+ ?? event?.metadata?.originatingTo
223
+ ?? ctx?.conversationId
224
+ ?? "";
225
+ const match = String(rawTo).match(/^(?:channel|dm|group):([A-Z0-9]+)$/i);
226
+ return match ? match[1].toUpperCase() : undefined;
227
+ }
228
+
229
+ /**
230
+ * Resolve the session key for the current turn from available ctx.
231
+ * Tries ctx.sessionKey first, then falls back to sessionId.
232
+ */
233
+ function resolveSessionKeyFromCtx(ctx: any): string | undefined {
234
+ const sk = ctx?.sessionKey?.trim?.();
235
+ if (sk) return sk;
236
+ const sid = ctx?.sessionId?.trim?.();
237
+ return sid || undefined;
238
+ }
239
+
240
+ /**
241
+ * Get or create turn state for a session.
242
+ */
243
+ export function getOrCreateTurnState(sessionKey: string): TurnState {
244
+ let state = turnStateBySession.get(sessionKey);
245
+ if (!state) {
246
+ state = createDefaultTurnState();
247
+ turnStateBySession.set(sessionKey, state);
248
+ }
249
+ return state;
250
+ }
251
+
252
+ /**
253
+ * Delete turn state for a session (cleanup after agent_end).
254
+ */
255
+ export function deleteTurnState(sessionKey: string): void {
256
+ turnStateBySession.delete(sessionKey);
257
+ }
258
+
259
+ /**
260
+ * Send an emoji reaction to a message via the Slack Web API (or Discord API).
261
+ * Only fires for supported channels (slack, discord). Silently no-ops for others.
262
+ *
263
+ * For Slack, calls reactions.add via the @slack/web-api client.
264
+ * Requires SLACK_BOT_TOKEN in the environment.
265
+ */
266
+ export async function sendReaction(
267
+ channelId: string,
268
+ messageId: string,
269
+ emoji: string,
270
+ provider: string,
271
+ ): Promise<void> {
272
+ if (!channelId || !messageId || !emoji) return;
273
+ if (!REACTION_SUPPORTED_PROVIDERS.has(provider)) return;
274
+
275
+ if (provider === "slack") {
276
+ await sendSlackReaction(channelId, messageId, emoji);
277
+ }
278
+ // Discord: future implementation
279
+ }
280
+
281
+ /** Cached Slack bot token resolved from env or OpenClaw config. */
282
+ let _cachedSlackToken: string | null | undefined;
283
+
284
+ /**
285
+ * Resolve the Slack bot token from environment or OpenClaw config file.
286
+ * Caches the result for the lifetime of the process.
287
+ *
288
+ * Resolution order:
289
+ * 1. SLACK_BOT_TOKEN env var (explicit override)
290
+ * 2. OpenClaw config: channels.slack.botToken (standard single-account)
291
+ * 3. OpenClaw config: channels.slack.accounts.default.botToken (multi-account)
292
+ *
293
+ * Config path: OPENCLAW_CONFIG env var → ~/.openclaw/openclaw.json
294
+ */
295
+ async function resolveSlackBotToken(): Promise<string | null> {
296
+ if (_cachedSlackToken !== undefined) return _cachedSlackToken;
297
+
298
+ // 1) Environment variable
299
+ const envToken = process.env.SLACK_BOT_TOKEN?.trim();
300
+ if (envToken) {
301
+ _cachedSlackToken = envToken;
302
+ return envToken;
303
+ }
304
+
305
+ // 2) OpenClaw config file — OPENCLAW_CONFIG takes precedence over default path
306
+ const configPaths = [
307
+ process.env.OPENCLAW_CONFIG || "",
308
+ path.join(os.homedir(), ".openclaw", "openclaw.json"),
309
+ ].filter(Boolean);
310
+
311
+ for (const configPath of configPaths) {
312
+ try {
313
+ const raw = await fs.readFile(configPath, "utf-8");
314
+ const config = JSON.parse(raw);
315
+
316
+ // 2a) Standard path: channels.slack.botToken
317
+ const directToken = config?.channels?.slack?.botToken?.trim();
318
+ if (directToken) {
319
+ _cachedSlackToken = directToken;
320
+ return directToken;
321
+ }
322
+
323
+ // 2b) Multi-account path: channels.slack.accounts.default.botToken
324
+ const accountToken = config?.channels?.slack?.accounts?.default?.botToken?.trim();
325
+ if (accountToken) {
326
+ _cachedSlackToken = accountToken;
327
+ return accountToken;
328
+ }
329
+ } catch {
330
+ // Try next path
331
+ }
332
+ }
333
+
334
+ _cachedSlackToken = null;
335
+ return null;
336
+ }
337
+
338
+ /** Reset cached token (for testing). */
339
+ export function resetSlackTokenCache(): void {
340
+ _cachedSlackToken = undefined;
341
+ }
342
+
343
+ async function sendSlackReaction(
344
+ channelId: string,
345
+ messageId: string,
346
+ emoji: string,
347
+ ): Promise<void> {
348
+ const token = await resolveSlackBotToken();
349
+ if (!token) {
350
+ console.warn("[palaia] Cannot send Slack reaction: no bot token found");
351
+ return;
352
+ }
353
+
354
+ const normalizedEmoji = emoji.replace(/^:/, "").replace(/:$/, "");
355
+
356
+ const controller = new AbortController();
357
+ const timeout = setTimeout(() => controller.abort(), 5000);
358
+
359
+ try {
360
+ const response = await fetch("https://slack.com/api/reactions.add", {
361
+ method: "POST",
362
+ headers: {
363
+ "Content-Type": "application/json; charset=utf-8",
364
+ Authorization: `Bearer ${token}`,
365
+ },
366
+ body: JSON.stringify({
367
+ channel: channelId,
368
+ timestamp: messageId,
369
+ name: normalizedEmoji,
370
+ }),
371
+ signal: controller.signal,
372
+ });
373
+ const data = await response.json() as { ok: boolean; error?: string };
374
+ if (!data.ok && data.error !== "already_reacted") {
375
+ console.warn(`[palaia] Slack reaction failed: ${data.error} (${normalizedEmoji} on ${channelId})`);
376
+ }
377
+ } catch (err) {
378
+ if ((err as Error).name !== "AbortError") {
379
+ console.warn(`[palaia] Slack reaction error (${normalizedEmoji}): ${err}`);
380
+ }
381
+ } finally {
382
+ clearTimeout(timeout);
383
+ }
384
+ }
385
+
386
+ // ============================================================================
387
+ // Footnote Helpers (Issue #87)
388
+ // ============================================================================
389
+
390
+ /**
391
+ * Format an ISO date string as a short date: "Mar 16", "Feb 10".
392
+ */
393
+ export function formatShortDate(isoDate: string): string {
394
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
395
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
396
+ try {
397
+ const d = new Date(isoDate);
398
+ if (isNaN(d.getTime())) return "";
399
+ return `${months[d.getMonth()]} ${d.getDate()}`;
400
+ } catch {
401
+ return "";
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Check if an injected entry is relevant to the response text.
407
+ * Simple keyword overlap: split title into words, check if >=2 words appear
408
+ * in the response (case-insensitive). Words shorter than 3 chars are skipped.
409
+ */
410
+ export function isEntryRelevant(title: string, responseText: string): boolean {
411
+ const responseLower = responseText.toLowerCase();
412
+ const titleWords = title
413
+ .toLowerCase()
414
+ .split(/[\s\-_/]+/)
415
+ .filter((w) => w.length >= 3);
416
+ if (titleWords.length === 0) return false;
417
+ const threshold = titleWords.length === 1 ? 1 : 2;
418
+ let matches = 0;
419
+ for (const word of titleWords) {
420
+ if (responseLower.includes(word)) {
421
+ matches++;
422
+ if (matches >= threshold) return true;
423
+ }
424
+ }
425
+ return false;
426
+ }
427
+
428
+ /**
429
+ * Build a memory source footnote string from injected entries and response text.
430
+ * Returns null if no relevant entries found.
431
+ */
432
+ export function buildFootnote(
433
+ entries: Array<{ title: string; date: string }>,
434
+ _responseText: string,
435
+ maxEntries = 3,
436
+ ): string | null {
437
+ if (entries.length === 0) return null;
438
+
439
+ const display = entries.slice(0, maxEntries);
440
+ const parts = display.map((e) => {
441
+ const dateStr = formatShortDate(e.date);
442
+ return dateStr ? `"${e.title}" (${dateStr})` : `"${e.title}"`;
443
+ });
444
+ return `\n\n📎 Palaia: ${parts.join(", ")}`;
445
+ }
446
+
447
+ // ============================================================================
448
+ // Satisfaction / Transparency Nudge Helpers (Issue #87)
449
+ // ============================================================================
450
+
451
+ const SATISFACTION_THRESHOLD = 10;
452
+ const TRANSPARENCY_RECALL_THRESHOLD = 50;
453
+ const TRANSPARENCY_DAYS_THRESHOLD = 7;
454
+
455
+ const SATISFACTION_NUDGE_TEXT =
456
+ "Your user has been using Palaia for a while now. " +
457
+ "Ask them casually if they're happy with the memory system. " +
458
+ "If there are issues, suggest `palaia doctor`.";
459
+
460
+ const TRANSPARENCY_NUDGE_TEXT =
461
+ "Your user has been seeing memory Footnotes and capture confirmations for several days. " +
462
+ "Ask them once: 'Would you like to keep seeing memory source references and capture " +
463
+ "confirmations, or should I hide them? You can change this anytime.' " +
464
+ "Based on their answer: `palaia config set showMemorySources true/false` and " +
465
+ "`palaia config set showCaptureConfirm true/false`";
466
+
467
+ /**
468
+ * Check which nudges (if any) should fire based on plugin state.
469
+ * Returns nudge texts to prepend, and updates state accordingly.
470
+ */
471
+ export function checkNudges(state: PluginState): { nudges: string[]; updated: boolean } {
472
+ const nudges: string[] = [];
473
+ let updated = false;
474
+
475
+ if (!state.satisfactionNudged && state.successfulRecalls >= SATISFACTION_THRESHOLD) {
476
+ nudges.push(SATISFACTION_NUDGE_TEXT);
477
+ state.satisfactionNudged = true;
478
+ updated = true;
479
+ }
480
+
481
+ if (!state.transparencyNudged && state.firstRecallTimestamp) {
482
+ const daysSinceFirst = (Date.now() - new Date(state.firstRecallTimestamp).getTime()) / (1000 * 60 * 60 * 24);
483
+ if (state.successfulRecalls >= TRANSPARENCY_RECALL_THRESHOLD || daysSinceFirst >= TRANSPARENCY_DAYS_THRESHOLD) {
484
+ nudges.push(TRANSPARENCY_NUDGE_TEXT);
485
+ state.transparencyNudged = true;
486
+ updated = true;
487
+ }
488
+ }
489
+
490
+ return { nudges, updated };
491
+ }
492
+
493
+ // ============================================================================
494
+ // Capture Hints (Issue #81)
495
+ // ============================================================================
496
+
497
+ /** Parsed palaia-hint tag attributes */
498
+ export interface PalaiaHint {
499
+ project?: string;
500
+ scope?: string;
501
+ type?: string;
502
+ tags?: string[];
503
+ }
504
+
505
+ /**
506
+ * Parse `<palaia-hint ... />` tags from text.
507
+ * Returns extracted hints and cleaned text with hints removed.
508
+ */
509
+ export function parsePalaiaHints(text: string): { hints: PalaiaHint[]; cleanedText: string } {
510
+ const hints: PalaiaHint[] = [];
511
+ const regex = /<palaia-hint\s+([^/]*)\s*\/>/gi;
512
+
513
+ let match: RegExpExecArray | null;
514
+ while ((match = regex.exec(text)) !== null) {
515
+ const attrs = match[1];
516
+ const hint: PalaiaHint = {};
517
+
518
+ const projectMatch = attrs.match(/project\s*=\s*"([^"]*)"/i);
519
+ if (projectMatch) hint.project = projectMatch[1];
520
+
521
+ const scopeMatch = attrs.match(/scope\s*=\s*"([^"]*)"/i);
522
+ if (scopeMatch) hint.scope = scopeMatch[1];
523
+
524
+ const typeMatch = attrs.match(/type\s*=\s*"([^"]*)"/i);
525
+ if (typeMatch) hint.type = typeMatch[1];
526
+
527
+ const tagsMatch = attrs.match(/tags\s*=\s*"([^"]*)"/i);
528
+ if (tagsMatch) hint.tags = tagsMatch[1].split(",").map((t) => t.trim()).filter(Boolean);
529
+
530
+ hints.push(hint);
531
+ }
532
+
533
+ const cleanedText = text.replace(/<palaia-hint\s+[^/]*\s*\/>/gi, "").trim();
534
+ return { hints, cleanedText };
535
+ }
536
+
537
+ // ============================================================================
538
+ // Project Cache (Issue #81)
539
+ // ============================================================================
540
+
541
+ interface CachedProject {
542
+ name: string;
543
+ description?: string;
544
+ }
545
+
546
+ let _cachedProjects: CachedProject[] | null = null;
547
+ let _projectCacheTime = 0;
548
+ const PROJECT_CACHE_TTL_MS = 60_000;
549
+
550
+ /** Reset project cache (for testing). */
551
+ export function resetProjectCache(): void {
552
+ _cachedProjects = null;
553
+ _projectCacheTime = 0;
554
+ }
555
+
556
+ /**
557
+ * Load known projects from CLI, with caching.
558
+ */
559
+ async function loadProjects(opts: import("./runner.js").RunnerOpts): Promise<CachedProject[]> {
560
+ const now = Date.now();
561
+ if (_cachedProjects && (now - _projectCacheTime) < PROJECT_CACHE_TTL_MS) {
562
+ return _cachedProjects;
563
+ }
564
+
565
+ try {
566
+ const result = await runJson<{ projects: Array<{ name: string; description?: string }> }>(
567
+ ["project", "list"],
568
+ opts,
569
+ );
570
+ _cachedProjects = (result.projects || []).map((p) => ({
571
+ name: p.name,
572
+ description: p.description,
573
+ }));
574
+ _projectCacheTime = now;
575
+ return _cachedProjects;
576
+ } catch {
577
+ return _cachedProjects || [];
578
+ }
579
+ }
580
+
581
+ // ============================================================================
582
+ // Types
583
+ // ============================================================================
584
+
585
+ /** Shape returned by `palaia query --json` or `palaia list --json` */
12
586
  interface QueryResult {
13
587
  results: Array<{
14
588
  id: string;
@@ -18,12 +592,574 @@ interface QueryResult {
18
592
  tier: string;
19
593
  scope: string;
20
594
  title?: string;
595
+ type?: string;
596
+ tags?: string[];
21
597
  }>;
22
598
  }
23
599
 
600
+ /** Message shape from OpenClaw event.messages */
601
+ interface Message {
602
+ role?: string;
603
+ content?: string | Array<{ type?: string; text?: string }>;
604
+ }
605
+
606
+ // ============================================================================
607
+ // LLM-based Extraction (Issue #64 upgrade)
608
+ // ============================================================================
609
+
610
+ /** Result from LLM-based knowledge extraction */
611
+ export interface ExtractionResult {
612
+ content: string;
613
+ type: "memory" | "process" | "task";
614
+ tags: string[];
615
+ significance: number;
616
+ project?: string | null;
617
+ scope?: string | null;
618
+ }
619
+
620
+ type RunEmbeddedPiAgentFn = (params: Record<string, unknown>) => Promise<unknown>;
621
+
622
+ let _embeddedPiAgentLoader: Promise<RunEmbeddedPiAgentFn> | null = null;
623
+ /** Whether the LLM import failure has already been logged (to avoid spam). */
624
+ let _llmImportFailureLogged = false;
625
+
626
+ /**
627
+ * Resolve the path to OpenClaw's extensionAPI module.
628
+ * Uses multiple strategies for portability across installation layouts.
629
+ */
630
+ function resolveExtensionAPIPath(): string | null {
631
+ // Strategy 1: require.resolve with openclaw package exports
632
+ try {
633
+ return require.resolve("openclaw/dist/extensionAPI.js");
634
+ } catch {
635
+ // Not resolvable via standard module resolution
636
+ }
637
+
638
+ // Strategy 2: Resolve openclaw main entry, then navigate to dist/extensionAPI.js
639
+ try {
640
+ const openclawMain = require.resolve("openclaw");
641
+ const candidate = path.join(path.dirname(openclawMain), "extensionAPI.js");
642
+ if (require("node:fs").existsSync(candidate)) return candidate;
643
+ } catch {
644
+ // openclaw not resolvable at all
645
+ }
646
+
647
+ // Strategy 3: Sibling in global node_modules (plugin installed alongside openclaw)
648
+ try {
649
+ const thisFile = typeof __dirname !== "undefined" ? __dirname : path.dirname(new URL(import.meta.url).pathname);
650
+ // Walk up from plugin src/dist to node_modules, then into openclaw
651
+ let dir = thisFile;
652
+ for (let i = 0; i < 6; i++) {
653
+ const candidate = path.join(dir, "openclaw", "dist", "extensionAPI.js");
654
+ if (require("node:fs").existsSync(candidate)) return candidate;
655
+ const parent = path.dirname(dir);
656
+ if (parent === dir) break;
657
+ dir = parent;
658
+ }
659
+ } catch {
660
+ // Traversal failed
661
+ }
662
+
663
+ // Strategy 4: Well-known global install paths
664
+ const globalCandidates = [
665
+ path.join(os.homedir(), ".openclaw", "node_modules", "openclaw", "dist", "extensionAPI.js"),
666
+ "/home/linuxbrew/.linuxbrew/lib/node_modules/openclaw/dist/extensionAPI.js",
667
+ "/usr/local/lib/node_modules/openclaw/dist/extensionAPI.js",
668
+ "/usr/lib/node_modules/openclaw/dist/extensionAPI.js",
669
+ ];
670
+ for (const candidate of globalCandidates) {
671
+ try {
672
+ if (require("node:fs").existsSync(candidate)) return candidate;
673
+ } catch {
674
+ // skip
675
+ }
676
+ }
677
+
678
+ return null;
679
+ }
680
+
681
+ async function loadRunEmbeddedPiAgent(): Promise<RunEmbeddedPiAgentFn> {
682
+ const resolved = resolveExtensionAPIPath();
683
+ if (!resolved) {
684
+ throw new Error("Could not locate openclaw/dist/extensionAPI.js — tried module resolution, sibling lookup, and global paths");
685
+ }
686
+
687
+ const mod = (await import(resolved)) as { runEmbeddedPiAgent?: unknown };
688
+ const fn = (mod as any).runEmbeddedPiAgent;
689
+ if (typeof fn !== "function") {
690
+ throw new Error(`runEmbeddedPiAgent not exported from ${resolved}`);
691
+ }
692
+ return fn as RunEmbeddedPiAgentFn;
693
+ }
694
+
695
+ export function getEmbeddedPiAgent(): Promise<RunEmbeddedPiAgentFn> {
696
+ if (!_embeddedPiAgentLoader) {
697
+ _embeddedPiAgentLoader = loadRunEmbeddedPiAgent();
698
+ }
699
+ return _embeddedPiAgentLoader;
700
+ }
701
+
702
+ /** Reset cached loader (for testing). */
703
+ export function resetEmbeddedPiAgentLoader(): void {
704
+ _embeddedPiAgentLoader = null;
705
+ _llmImportFailureLogged = false;
706
+ }
707
+
708
+ /** Override the cached loader with a custom promise (for testing). */
709
+ export function setEmbeddedPiAgentLoader(loader: Promise<RunEmbeddedPiAgentFn> | null): void {
710
+ _embeddedPiAgentLoader = loader;
711
+ }
712
+
713
+ const EXTRACTION_SYSTEM_PROMPT_BASE = `You are a knowledge extraction engine. Analyze the following conversation exchange and identify information worth remembering long-term.
714
+
715
+ For each piece of knowledge, return a JSON array of objects:
716
+ - "content": concise summary of the knowledge (1-3 sentences)
717
+ - "type": "memory" (facts, decisions, preferences), "process" (workflows, procedures, steps), or "task" (action items, todos, commitments)
718
+ - "tags": array of significance tags from: ["decision", "lesson", "surprise", "commitment", "correction", "preference", "fact"]
719
+ - "significance": 0.0-1.0 how important this is for long-term recall
720
+ - "project": which project this belongs to (from known projects list, or null if unclear)
721
+ - "scope": "private" (personal preference, agent-specific), "team" (shared knowledge), or "public" (documentation)
722
+
723
+ Only extract genuinely significant knowledge. Skip small talk, acknowledgments, routine exchanges.
724
+ Return empty array [] if nothing is worth remembering.
725
+ Return ONLY valid JSON, no markdown fences.`;
726
+
727
+ function buildExtractionPrompt(projects: CachedProject[]): string {
728
+ if (projects.length === 0) return EXTRACTION_SYSTEM_PROMPT_BASE;
729
+ const projectList = projects
730
+ .map((p) => `${p.name}${p.description ? ` (${p.description})` : ""}`)
731
+ .join(", ");
732
+ return `${EXTRACTION_SYSTEM_PROMPT_BASE}\n\nKnown projects: ${projectList}`;
733
+ }
734
+
735
+ /** Whether the captureModel fallback warning has already been logged (to avoid spam). */
736
+ let _captureModelFallbackWarned = false;
737
+
738
+ /** Whether the captureModel→primary model fallback warning has been logged (max 1x per gateway lifetime). */
739
+ let _captureModelFailoverWarned = false;
740
+
741
+ /** Reset captureModel fallback warning flag (for testing). */
742
+ export function resetCaptureModelFallbackWarning(): void {
743
+ _captureModelFallbackWarned = false;
744
+ _captureModelFailoverWarned = false;
745
+ }
746
+
24
747
  /**
25
- * Build RunnerOpts from plugin config.
748
+ * Resolve the model to use for LLM-based capture extraction.
749
+ *
750
+ * Strategy (no static model mapping — user config is the source of truth):
751
+ * 1. If captureModel is set explicitly (e.g. "anthropic/claude-haiku-4-5"): use it directly.
752
+ * 2. If captureModel is unset: use the primary model from user config.
753
+ * Log a one-time warning recommending to set a cheaper captureModel.
754
+ * 3. Never fall back to static model IDs — model IDs change and not every user has Anthropic.
26
755
  */
756
+ export function resolveCaptureModel(
757
+ config: any,
758
+ captureModel?: string,
759
+ ): { provider: string; model: string } | undefined {
760
+ // Case 1: explicit model ID provided (not "cheap")
761
+ if (captureModel && captureModel !== "cheap") {
762
+ const parts = captureModel.split("/");
763
+ if (parts.length >= 2) {
764
+ return { provider: parts[0], model: parts.slice(1).join("/") };
765
+ }
766
+ // No slash — treat as model name with provider from primary config
767
+ const defaultsModel = config?.agents?.defaults?.model;
768
+ const primary = typeof defaultsModel === "string"
769
+ ? defaultsModel.trim()
770
+ : (defaultsModel?.primary?.trim() ?? "");
771
+ const defaultProvider = primary.split("/")[0];
772
+ if (defaultProvider) {
773
+ return { provider: defaultProvider, model: captureModel };
774
+ }
775
+ }
776
+
777
+ // Case 2: "cheap" or unset — use primary model from user config
778
+ const defaultsModel = config?.agents?.defaults?.model;
779
+
780
+ const primary = typeof defaultsModel === "string"
781
+ ? defaultsModel.trim()
782
+ : (typeof defaultsModel === "object" && defaultsModel !== null
783
+ ? String(defaultsModel.primary ?? "").trim()
784
+ : "");
785
+
786
+ if (primary) {
787
+ const parts = primary.split("/");
788
+ if (parts.length >= 2) {
789
+ if (!_captureModelFallbackWarned) {
790
+ _captureModelFallbackWarned = true;
791
+ console.warn(`[palaia] No captureModel configured — using primary model. Set captureModel in plugin config for cost savings.`);
792
+ }
793
+ return { provider: parts[0], model: parts.slice(1).join("/") };
794
+ }
795
+ }
796
+
797
+ return undefined;
798
+ }
799
+
800
+ function stripCodeFences(s: string): string {
801
+ const trimmed = s.trim();
802
+ const m = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
803
+ if (m) return (m[1] ?? "").trim();
804
+ return trimmed;
805
+ }
806
+
807
+ function collectText(payloads: Array<{ text?: string; isError?: boolean }> | undefined): string {
808
+ return (payloads ?? [])
809
+ .filter((p) => !p.isError && typeof p.text === "string")
810
+ .map((p) => p.text ?? "")
811
+ .join("\n")
812
+ .trim();
813
+ }
814
+
815
+ /**
816
+ * Trim message texts to a recent window for LLM extraction.
817
+ * Only extract from recent exchanges — full history causes LLM timeouts
818
+ * and dilutes extraction quality.
819
+ *
820
+ * Strategy: keep last N user+assistant pairs (skip toolResult roles),
821
+ * then hard-cap at maxChars from the end (newest messages kept).
822
+ */
823
+ export function trimToRecentExchanges(
824
+ texts: Array<{ role: string; text: string }>,
825
+ maxPairs = 5,
826
+ maxChars = 10_000,
827
+ ): Array<{ role: string; text: string }> {
828
+ // Filter to only user + assistant messages (skip tool, toolResult, system, etc.)
829
+ const exchanges = texts.filter((t) => t.role === "user" || t.role === "assistant");
830
+
831
+ // Keep the last N pairs (a pair = one user + one assistant message)
832
+ // Walk backwards, count pairs
833
+ let pairCount = 0;
834
+ let lastRole = "";
835
+ let cutIndex = 0; // default: keep everything
836
+ for (let i = exchanges.length - 1; i >= 0; i--) {
837
+ // Count a new pair when we see a user message after having seen an assistant
838
+ if (exchanges[i].role === "user" && lastRole === "assistant") {
839
+ pairCount++;
840
+ if (pairCount > maxPairs) {
841
+ cutIndex = i + 1; // keep from next message onwards
842
+ break;
843
+ }
844
+ }
845
+ if (exchanges[i].role !== lastRole) {
846
+ lastRole = exchanges[i].role;
847
+ }
848
+ }
849
+ let trimmed = exchanges.slice(cutIndex);
850
+
851
+ // Hard cap: max chars from the end (keep newest)
852
+ let totalChars = trimmed.reduce((sum, t) => sum + t.text.length + t.role.length + 5, 0);
853
+ while (totalChars > maxChars && trimmed.length > 1) {
854
+ const removed = trimmed.shift()!;
855
+ totalChars -= removed.text.length + removed.role.length + 5;
856
+ }
857
+
858
+ return trimmed;
859
+ }
860
+
861
+ export async function extractWithLLM(
862
+ messages: unknown[],
863
+ config: any,
864
+ pluginConfig?: { captureModel?: string },
865
+ knownProjects?: CachedProject[],
866
+ ): Promise<ExtractionResult[]> {
867
+ const runEmbeddedPiAgent = await getEmbeddedPiAgent();
868
+
869
+ const resolved = resolveCaptureModel(config, pluginConfig?.captureModel);
870
+ if (!resolved) {
871
+ throw new Error("No model available for LLM extraction");
872
+ }
873
+
874
+ const allTexts = extractMessageTexts(messages);
875
+ // Only extract from recent exchanges — full history causes LLM timeouts
876
+ // and dilutes extraction quality
877
+ const recentTexts = trimToRecentExchanges(allTexts);
878
+ const exchangeText = recentTexts
879
+ .map((t) => `[${t.role}]: ${t.text}`)
880
+ .join("\n");
881
+
882
+ if (!exchangeText.trim()) {
883
+ return [];
884
+ }
885
+
886
+ const systemPrompt = buildExtractionPrompt(knownProjects || []);
887
+ const prompt = `${systemPrompt}\n\n--- CONVERSATION ---\n${exchangeText}\n--- END ---`;
888
+
889
+ let tmpDir: string | null = null;
890
+ try {
891
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "palaia-extract-"));
892
+ const sessionId = `palaia-extract-${Date.now()}`;
893
+ const sessionFile = path.join(tmpDir, "session.json");
894
+
895
+ const result = await runEmbeddedPiAgent({
896
+ sessionId,
897
+ sessionFile,
898
+ workspaceDir: config?.agents?.defaults?.workspace ?? process.cwd(),
899
+ config,
900
+ prompt,
901
+ timeoutMs: 15_000,
902
+ runId: `palaia-extract-${Date.now()}`,
903
+ provider: resolved.provider,
904
+ model: resolved.model,
905
+ disableTools: true,
906
+ streamParams: { maxTokens: 2048 },
907
+ });
908
+
909
+ const text = collectText((result as any).payloads);
910
+ if (!text) return [];
911
+
912
+ const raw = stripCodeFences(text);
913
+ let parsed: unknown;
914
+ try {
915
+ parsed = JSON.parse(raw);
916
+ } catch {
917
+ throw new Error(`LLM returned invalid JSON: ${raw.slice(0, 200)}`);
918
+ }
919
+
920
+ if (!Array.isArray(parsed)) {
921
+ throw new Error(`LLM returned non-array: ${typeof parsed}`);
922
+ }
923
+
924
+ const results: ExtractionResult[] = [];
925
+ for (const item of parsed) {
926
+ if (!item || typeof item !== "object") continue;
927
+ const content = typeof item.content === "string" ? item.content.trim() : "";
928
+ if (!content) continue;
929
+
930
+ const validTypes = new Set(["memory", "process", "task"]);
931
+ const type = validTypes.has(item.type) ? item.type : "memory";
932
+
933
+ const validTags = new Set([
934
+ "decision", "lesson", "surprise", "commitment",
935
+ "correction", "preference", "fact",
936
+ ]);
937
+ const tags = Array.isArray(item.tags)
938
+ ? item.tags.filter((t: unknown) => typeof t === "string" && validTags.has(t))
939
+ : [];
940
+
941
+ const significance = typeof item.significance === "number"
942
+ ? Math.max(0, Math.min(1, item.significance))
943
+ : 0.5;
944
+
945
+ const project = typeof item.project === "string" && item.project.trim()
946
+ ? item.project.trim()
947
+ : null;
948
+
949
+ const scope = typeof item.scope === "string" && isValidScope(item.scope)
950
+ ? item.scope
951
+ : null;
952
+
953
+ results.push({ content, type, tags, significance, project, scope });
954
+ }
955
+
956
+ return results;
957
+ } finally {
958
+ if (tmpDir) {
959
+ try { await fs.rm(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
960
+ }
961
+ }
962
+ }
963
+
964
+ // ============================================================================
965
+ // Auto-Capture: Rule-based extraction (Issue #64)
966
+ // ============================================================================
967
+
968
+ const TRIVIAL_RESPONSES = new Set([
969
+ "ok", "ja", "nein", "yes", "no", "sure", "klar", "danke", "thanks",
970
+ "thx", "k", "👍", "👎", "ack", "nope", "yep", "yup", "alright",
971
+ "fine", "gut", "passt", "okay", "hmm", "hm", "ah", "aha",
972
+ ]);
973
+
974
+ const SIGNIFICANCE_RULES: Array<{
975
+ pattern: RegExp;
976
+ tag: string;
977
+ type: "memory" | "process" | "task";
978
+ }> = [
979
+ { pattern: /(?:we decided|entschieden|decision:|beschlossen|let'?s go with|wir nehmen|agreed on)/i, tag: "decision", type: "memory" },
980
+ { pattern: /(?:will use|werden nutzen|going forward|ab jetzt|from now on)/i, tag: "decision", type: "memory" },
981
+ { pattern: /(?:learned|gelernt|lesson:|erkenntnis|takeaway|insight|turns out|it seems)/i, tag: "lesson", type: "memory" },
982
+ { pattern: /(?:mistake was|fehler war|should have|hätten sollen|next time)/i, tag: "lesson", type: "memory" },
983
+ { pattern: /(?:surprising|überraschend|unexpected|unerwartet|didn'?t expect|nicht erwartet|plot twist)/i, tag: "surprise", type: "memory" },
984
+ { pattern: /(?:i will|ich werde|todo:|action item|must do|muss noch|need to|commit to|verspreche)/i, tag: "commitment", type: "task" },
985
+ { pattern: /(?:deadline|frist|due date|bis zum|by end of|spätestens)/i, tag: "commitment", type: "task" },
986
+ { pattern: /(?:the process is|der prozess|steps?:|workflow:|how to|anleitung|recipe:|checklist)/i, tag: "process", type: "process" },
987
+ { pattern: /(?:first,?\s.*then|schritt \d|step \d|1\.\s.*2\.\s)/i, tag: "process", type: "process" },
988
+ ];
989
+
990
+ const NOISE_PATTERNS: RegExp[] = [
991
+ /(?:PASSED|FAILED|ERROR)\s+\[?\d+%\]?/i,
992
+ /(?:test_\w+|tests?\/\w+\.(?:py|ts|js))\s*::/,
993
+ /(?:pytest|vitest|jest|mocha)\s+(?:run|--)/i,
994
+ /\d+ passed,?\s*\d* (?:failed|error|warning)/i,
995
+ /^(?:=+\s*(?:test session|ERRORS|FAILURES|short test summary))/m,
996
+ /(?:Traceback \(most recent call last\)|^\s+File ".*", line \d+)/m,
997
+ /^\s+at\s+\S+\s+\(.*:\d+:\d+\)/m,
998
+ /^(?:\/[\w/.-]+){3,}\s*$/m,
999
+ /(?:npm\s+(?:ERR|WARN)|pip\s+install|cargo\s+build)/i,
1000
+ /^(?:warning|error)\[?\w*\]?:\s/m,
1001
+ ];
1002
+
1003
+ export function isNoiseContent(text: string): boolean {
1004
+ let matchCount = 0;
1005
+ for (const pattern of NOISE_PATTERNS) {
1006
+ if (pattern.test(text)) {
1007
+ matchCount++;
1008
+ if (matchCount >= 2) return true;
1009
+ }
1010
+ }
1011
+
1012
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
1013
+ if (lines.length > 3) {
1014
+ const pathLines = lines.filter((l) => /^\s*(?:\/[\w/.-]+){2,}/.test(l.trim()));
1015
+ if (pathLines.length / lines.length > 0.5) return true;
1016
+ }
1017
+
1018
+ return false;
1019
+ }
1020
+
1021
+ export function shouldAttemptCapture(
1022
+ exchangeText: string,
1023
+ minChars = 100,
1024
+ ): boolean {
1025
+ const trimmed = exchangeText.trim();
1026
+
1027
+ if (trimmed.length < minChars) return false;
1028
+
1029
+ const words = trimmed.toLowerCase().split(/\s+/);
1030
+ if (words.length <= 3 && words.every((w) => TRIVIAL_RESPONSES.has(w))) {
1031
+ return false;
1032
+ }
1033
+
1034
+ if (trimmed.includes("<relevant-memories>")) return false;
1035
+ if (trimmed.startsWith("<") && trimmed.includes("</")) return false;
1036
+
1037
+ if (isNoiseContent(trimmed)) return false;
1038
+
1039
+ return true;
1040
+ }
1041
+
1042
+ export function extractSignificance(
1043
+ exchangeText: string,
1044
+ ): { tags: string[]; type: "memory" | "process" | "task"; summary: string } | null {
1045
+ const matched: Array<{ tag: string; type: "memory" | "process" | "task" }> = [];
1046
+
1047
+ for (const rule of SIGNIFICANCE_RULES) {
1048
+ if (rule.pattern.test(exchangeText)) {
1049
+ matched.push({ tag: rule.tag, type: rule.type });
1050
+ }
1051
+ }
1052
+
1053
+ if (matched.length === 0) return null;
1054
+
1055
+ const typePriority: Record<string, number> = { task: 3, process: 2, memory: 1 };
1056
+ const primaryType = matched.reduce(
1057
+ (best, m) => (typePriority[m.type] > typePriority[best] ? m.type : best),
1058
+ "memory" as "memory" | "process" | "task",
1059
+ );
1060
+
1061
+ const tags = [...new Set(matched.map((m) => m.tag))];
1062
+
1063
+ const sentences = exchangeText
1064
+ .split(/[.!?\n]+/)
1065
+ .map((s) => s.trim())
1066
+ .filter((s) => s.length > 20 && s.length < 500);
1067
+
1068
+ const relevantSentences = sentences.filter((s) =>
1069
+ SIGNIFICANCE_RULES.some((r) => r.pattern.test(s)),
1070
+ );
1071
+
1072
+ const summary = (relevantSentences.length > 0 ? relevantSentences : sentences)
1073
+ .slice(0, 3)
1074
+ .join(". ")
1075
+ .slice(0, 500);
1076
+
1077
+ if (!summary) return null;
1078
+
1079
+ return { tags, type: primaryType, summary };
1080
+ }
1081
+
1082
+ export function extractMessageTexts(messages: unknown[]): Array<{ role: string; text: string }> {
1083
+ const result: Array<{ role: string; text: string }> = [];
1084
+
1085
+ for (const msg of messages) {
1086
+ if (!msg || typeof msg !== "object") continue;
1087
+ const m = msg as Message;
1088
+ const role = m.role;
1089
+ if (!role || typeof role !== "string") continue;
1090
+
1091
+ if (typeof m.content === "string" && m.content.trim()) {
1092
+ result.push({ role, text: m.content.trim() });
1093
+ continue;
1094
+ }
1095
+
1096
+ if (Array.isArray(m.content)) {
1097
+ for (const block of m.content) {
1098
+ if (
1099
+ block &&
1100
+ typeof block === "object" &&
1101
+ block.type === "text" &&
1102
+ typeof block.text === "string" &&
1103
+ block.text.trim()
1104
+ ) {
1105
+ result.push({ role, text: block.text.trim() });
1106
+ }
1107
+ }
1108
+ }
1109
+ }
1110
+
1111
+ return result;
1112
+ }
1113
+
1114
+ export function getLastUserMessage(messages: unknown[]): string | null {
1115
+ const texts = extractMessageTexts(messages);
1116
+ for (let i = texts.length - 1; i >= 0; i--) {
1117
+ if (texts[i].role === "user") return texts[i].text;
1118
+ }
1119
+ return null;
1120
+ }
1121
+
1122
+ // ============================================================================
1123
+ // Query-based Recall: Type-weighted reranking (Issue #65)
1124
+ // ============================================================================
1125
+
1126
+ interface RankedEntry {
1127
+ id: string;
1128
+ body: string;
1129
+ title: string;
1130
+ scope: string;
1131
+ tier: string;
1132
+ type: string;
1133
+ score: number;
1134
+ weightedScore: number;
1135
+ }
1136
+
1137
+ export function rerankByTypeWeight(
1138
+ results: QueryResult["results"],
1139
+ weights: RecallTypeWeights,
1140
+ ): RankedEntry[] {
1141
+ return results
1142
+ .map((r) => {
1143
+ const type = r.type || "memory";
1144
+ const weight = weights[type] ?? 1.0;
1145
+ return {
1146
+ id: r.id,
1147
+ body: r.content || r.body || "",
1148
+ title: r.title || "(untitled)",
1149
+ scope: r.scope,
1150
+ tier: r.tier,
1151
+ type,
1152
+ score: r.score,
1153
+ weightedScore: r.score * weight,
1154
+ };
1155
+ })
1156
+ .sort((a, b) => b.weightedScore - a.weightedScore);
1157
+ }
1158
+
1159
+ // ============================================================================
1160
+ // Hook helpers
1161
+ // ============================================================================
1162
+
27
1163
  function buildRunnerOpts(config: PalaiaPluginConfig): RunnerOpts {
28
1164
  return {
29
1165
  binaryPath: config.binaryPath,
@@ -32,57 +1168,555 @@ function buildRunnerOpts(config: PalaiaPluginConfig): RunnerOpts {
32
1168
  };
33
1169
  }
34
1170
 
1171
+ // ============================================================================
1172
+ // /palaia status command — Format helpers
1173
+ // ============================================================================
1174
+
1175
+ function formatStatusResponse(
1176
+ state: PluginState,
1177
+ stats: Record<string, unknown>,
1178
+ config: PalaiaPluginConfig,
1179
+ ): string {
1180
+ const lines: string[] = ["Palaia Memory Status", ""];
1181
+
1182
+ // Recall count
1183
+ const sinceDate = state.firstRecallTimestamp
1184
+ ? formatShortDate(state.firstRecallTimestamp)
1185
+ : "n/a";
1186
+ lines.push(`Recalls: ${state.successfulRecalls} successful (since ${sinceDate})`);
1187
+
1188
+ // Store stats from palaia status --json
1189
+ const totalEntries = stats.total_entries ?? stats.totalEntries ?? "?";
1190
+ const hotEntries = stats.hot ?? stats.hotEntries ?? "?";
1191
+ const warmEntries = stats.warm ?? stats.warmEntries ?? "?";
1192
+ lines.push(`Store: ${totalEntries} entries (${hotEntries} hot, ${warmEntries} warm)`);
1193
+
1194
+ // Recall indicator
1195
+ lines.push(`Recall indicator: ${config.showMemorySources ? "ON" : "OFF"}`);
1196
+
1197
+ // Config summary
1198
+ lines.push(`Config: autoCapture=${config.autoCapture}, captureScope=${config.captureScope || "team"}`);
1199
+
1200
+ return lines.join("\n");
1201
+ }
1202
+
1203
+ // ============================================================================
1204
+ // Legacy exports kept for tests
1205
+ // ============================================================================
1206
+
1207
+ /** Reset all turn state, inbound message store, and cached tokens (for testing and cleanup). */
1208
+ export function resetTurnState(): void {
1209
+ turnStateBySession.clear();
1210
+ lastInboundMessageByChannel.clear();
1211
+ resetSlackTokenCache();
1212
+ }
1213
+
1214
+ // ============================================================================
1215
+ // Hook registration
1216
+ // ============================================================================
1217
+
35
1218
  /**
36
1219
  * Register lifecycle hooks on the plugin API.
37
1220
  */
38
1221
  export function registerHooks(api: any, config: PalaiaPluginConfig): void {
39
1222
  const opts = buildRunnerOpts(config);
40
1223
 
41
- // ── before_prompt_build ────────────────────────────────────────
42
- // Injects top HOT entries into agent system context.
43
- // Only active when config.memoryInject === true (default: false).
1224
+ // ── Startup checks (H-2, H-3) ─────────────────────────────────
1225
+ (async () => {
1226
+ // H-2: Warn if no agent is configured
1227
+ if (!process.env.PALAIA_AGENT) {
1228
+ try {
1229
+ const statusOut = await run(["config", "get", "agent"], { ...opts, timeoutMs: 3000 });
1230
+ if (!statusOut.trim()) {
1231
+ console.warn(
1232
+ "[palaia] No agent configured. Set PALAIA_AGENT env var or run 'palaia init --agent <name>'. " +
1233
+ "Auto-captured entries will have no agent attribution."
1234
+ );
1235
+ }
1236
+ } catch {
1237
+ console.warn(
1238
+ "[palaia] No agent configured. Set PALAIA_AGENT env var or run 'palaia init --agent <name>'. " +
1239
+ "Auto-captured entries will have no agent attribution."
1240
+ );
1241
+ }
1242
+ }
1243
+
1244
+ // H-3: Warn if no embedding provider beyond BM25
1245
+ try {
1246
+ const statusJson = await run(["status", "--json"], { ...opts, timeoutMs: 5000 });
1247
+ if (statusJson && statusJson.trim()) {
1248
+ const status = JSON.parse(statusJson);
1249
+ // embedding_chain can be at top level OR nested under config
1250
+ const chain = status.embedding_chain
1251
+ || status.embeddingChain
1252
+ || status.config?.embedding_chain
1253
+ || status.config?.embeddingChain
1254
+ || [];
1255
+ const hasSemanticProvider = Array.isArray(chain)
1256
+ ? chain.some((p: string) => p !== "bm25")
1257
+ : false;
1258
+ // Also check embedding_provider as a fallback signal
1259
+ const hasProviderConfig = !!(
1260
+ status.embedding_provider
1261
+ || status.config?.embedding_provider
1262
+ );
1263
+ if (!hasSemanticProvider && !hasProviderConfig) {
1264
+ console.warn(
1265
+ "[palaia] No embedding provider configured. Semantic search is inactive (BM25 keyword-only). " +
1266
+ "Run 'pip install palaia[fastembed]' and 'palaia doctor --fix' for better recall quality."
1267
+ );
1268
+ }
1269
+ }
1270
+ // If statusJson is empty/null, skip warning (CLI may not be available)
1271
+ } catch {
1272
+ // Non-fatal — status check failed, skip warning (avoid false positive)
1273
+ }
1274
+ })();
1275
+
1276
+ // ── /palaia status command ─────────────────────────────────────
1277
+ api.registerCommand({
1278
+ name: "palaia-status",
1279
+ description: "Show Palaia memory status",
1280
+ async handler(_args: string) {
1281
+ try {
1282
+ const state = await loadPluginState(config.workspace);
1283
+
1284
+ let stats: Record<string, unknown> = {};
1285
+ try {
1286
+ const statsOutput = await run(["status", "--json"], opts);
1287
+ stats = JSON.parse(statsOutput || "{}");
1288
+ } catch {
1289
+ // Non-fatal
1290
+ }
1291
+
1292
+ return { text: formatStatusResponse(state, stats, config) };
1293
+ } catch (error) {
1294
+ return { text: `Palaia status error: ${error}` };
1295
+ }
1296
+ },
1297
+ });
1298
+
1299
+ // ── message_received (capture inbound message ID for reactions) ─
1300
+ api.on("message_received", (event: any, ctx: any) => {
1301
+ try {
1302
+ const messageId = event?.metadata?.messageId;
1303
+ const provider = event?.metadata?.provider;
1304
+
1305
+ // ctx.channelId returns the provider name ("slack"), NOT the actual channel ID.
1306
+ // ctx.sessionKey is null during message_received.
1307
+ // Extract the real channel ID from event.metadata.to / ctx.conversationId.
1308
+ const channelId = extractChannelIdFromEvent(event, ctx)
1309
+ ?? (resolveSessionKeyFromCtx(ctx) ? extractSlackChannelIdFromSessionKey(resolveSessionKeyFromCtx(ctx)!) : undefined);
1310
+ const sessionKey = resolveSessionKeyFromCtx(ctx);
1311
+
1312
+
1313
+ if (messageId && channelId && provider && REACTION_SUPPORTED_PROVIDERS.has(provider)) {
1314
+ // Normalize channelId to UPPERCASE for consistent lookups
1315
+ // (extractSlackChannelIdFromSessionKey returns uppercase)
1316
+ const normalizedChannelId = String(channelId).toUpperCase();
1317
+ lastInboundMessageByChannel.set(normalizedChannelId, {
1318
+ messageId: String(messageId),
1319
+ provider,
1320
+ timestamp: Date.now(),
1321
+ });
1322
+
1323
+ // Also populate turnState if sessionKey is available
1324
+ if (sessionKey) {
1325
+ const turnState = getOrCreateTurnState(sessionKey);
1326
+ turnState.lastInboundMessageId = String(messageId);
1327
+ turnState.lastInboundChannelId = normalizedChannelId;
1328
+ turnState.channelProvider = provider;
1329
+ }
1330
+ }
1331
+ } catch {
1332
+ // Non-fatal — never block message flow
1333
+ }
1334
+ });
1335
+
1336
+ // ── before_prompt_build (Issue #65: Query-based Recall) ────────
44
1337
  if (config.memoryInject) {
45
1338
  api.on("before_prompt_build", async (event: any, ctx: any) => {
1339
+ // Prune stale entries to prevent memory leaks from crashed sessions (C-2)
1340
+ pruneStaleEntries();
1341
+
46
1342
  try {
47
1343
  const maxChars = config.maxInjectedChars || 4000;
48
1344
  const limit = Math.min(config.maxResults || 10, 20);
1345
+ let entries: QueryResult["results"] = [];
49
1346
 
50
- const result = await runJson<QueryResult>(
51
- ["list", "--tier", "hot", "--limit", String(limit)],
52
- opts
53
- );
1347
+ if (config.recallMode === "query") {
1348
+ const userMessage = event.prompt
1349
+ || (event.messages ? getLastUserMessage(event.messages) : null);
54
1350
 
55
- if (!result || !Array.isArray(result.results) || result.results.length === 0) {
56
- // Fallback: try query with empty string for recent entries
57
- return;
1351
+ if (userMessage && userMessage.length >= 5) {
1352
+ try {
1353
+ const queryArgs: string[] = ["query", userMessage, "--limit", String(limit)];
1354
+ if (config.tier === "all") {
1355
+ queryArgs.push("--all");
1356
+ }
1357
+ const result = await runJson<QueryResult>(queryArgs, opts);
1358
+ if (result && Array.isArray(result.results)) {
1359
+ entries = result.results;
1360
+ }
1361
+ } catch (queryError) {
1362
+ console.warn(`[palaia] Query recall failed, falling back to list: ${queryError}`);
1363
+ }
1364
+ }
1365
+ }
1366
+
1367
+ // Fallback: list mode
1368
+ if (entries.length === 0) {
1369
+ try {
1370
+ const listArgs: string[] = ["list"];
1371
+ if (config.tier === "all") {
1372
+ listArgs.push("--all");
1373
+ } else {
1374
+ listArgs.push("--tier", config.tier || "hot");
1375
+ }
1376
+ const result = await runJson<QueryResult>(listArgs, opts);
1377
+ if (result && Array.isArray(result.results)) {
1378
+ entries = result.results;
1379
+ }
1380
+ } catch {
1381
+ return;
1382
+ }
58
1383
  }
59
1384
 
60
- const entries = result.results;
1385
+ if (entries.length === 0) return;
1386
+
1387
+ // Apply type-weighted reranking
1388
+ const ranked = rerankByTypeWeight(entries, config.recallTypeWeight);
1389
+
1390
+ // Build context string with char budget
61
1391
  let text = "## Active Memory (Palaia)\n\n";
62
1392
  let chars = text.length;
63
1393
 
64
- for (const entry of entries) {
65
- const body = entry.content || entry.body || "";
66
- const title = entry.title || "(untitled)";
67
- const line = `**${title}** [${entry.scope}]\n${body}\n\n`;
68
-
1394
+ for (const entry of ranked) {
1395
+ const line = `**${entry.title}** [${entry.scope}/${entry.type}]\n${entry.body}\n\n`;
69
1396
  if (chars + line.length > maxChars) break;
70
1397
  text += line;
71
1398
  chars += line.length;
72
1399
  }
73
1400
 
74
- if (ctx.prependSystemContext) {
75
- ctx.prependSystemContext(text);
1401
+ // Update recall counter for satisfaction/transparency nudges (Issue #87)
1402
+ let nudgeContext = "";
1403
+ try {
1404
+ const pluginState = await loadPluginState(config.workspace);
1405
+ pluginState.successfulRecalls++;
1406
+ if (!pluginState.firstRecallTimestamp) {
1407
+ pluginState.firstRecallTimestamp = new Date().toISOString();
1408
+ }
1409
+ const { nudges } = checkNudges(pluginState);
1410
+ if (nudges.length > 0) {
1411
+ nudgeContext = "\n\n## Agent Nudge (Palaia)\n\n" + nudges.join("\n\n");
1412
+ }
1413
+ await savePluginState(pluginState, config.workspace);
1414
+ } catch {
1415
+ // Non-fatal
76
1416
  }
1417
+
1418
+ // Track recall in session-isolated turn state for emoji reactions
1419
+ const sessionKey = resolveSessionKeyFromCtx(ctx);
1420
+ if (sessionKey) {
1421
+ const turnState = getOrCreateTurnState(sessionKey);
1422
+ turnState.recallOccurred = true;
1423
+
1424
+ // Populate channel info — prefer event metadata, fall back to sessionKey
1425
+ const provider = extractChannelFromSessionKey(sessionKey);
1426
+ if (provider) turnState.channelProvider = provider;
1427
+ const slackChannel = extractChannelIdFromEvent(event, ctx)
1428
+ ?? extractSlackChannelIdFromSessionKey(sessionKey);
1429
+ if (slackChannel) turnState.lastInboundChannelId = slackChannel;
1430
+
1431
+ // Try to get the inbound message ID from the message_received store
1432
+ if (slackChannel) {
1433
+ const inbound = lastInboundMessageByChannel.get(slackChannel);
1434
+ if (inbound && (Date.now() - inbound.timestamp) < 30_000) {
1435
+ turnState.lastInboundMessageId = inbound.messageId;
1436
+ }
1437
+ }
1438
+ }
1439
+
1440
+ // Return prependContext + appendSystemContext for recall emoji
1441
+ return {
1442
+ prependContext: text + nudgeContext,
1443
+ appendSystemContext: config.showMemorySources
1444
+ ? "You used Palaia memory in this turn. Add 🧠 at the very end of your response (after everything else, on its own line)."
1445
+ : undefined,
1446
+ };
77
1447
  } catch (error) {
78
- // Non-fatal: if memory injection fails, agent continues without it
79
1448
  console.warn(`[palaia] Memory injection failed: ${error}`);
80
1449
  }
81
1450
  });
82
1451
  }
83
1452
 
1453
+ // ── message_sending (Issue #81: Hint stripping) ──────────────────
1454
+ api.on("message_sending", (_event: any, _ctx: any) => {
1455
+ const content = _event?.content;
1456
+ if (typeof content !== "string") return;
1457
+
1458
+ const { hints, cleanedText } = parsePalaiaHints(content);
1459
+ if (hints.length > 0) {
1460
+ return { content: cleanedText };
1461
+ }
1462
+ });
1463
+
1464
+ // ── agent_end (Issue #64 + #81: Auto-Capture with Metadata + Reactions) ───
1465
+ if (config.autoCapture) {
1466
+ api.on("agent_end", async (event: any, ctx: any) => {
1467
+ // Resolve session key for turn state
1468
+ const sessionKey = resolveSessionKeyFromCtx(ctx);
1469
+
1470
+ // DEBUG: always log agent_end firing
1471
+
1472
+ if (!event.success || !event.messages || event.messages.length === 0) {
1473
+ return;
1474
+ }
1475
+
1476
+ try {
1477
+ const agentName = process.env.PALAIA_AGENT || undefined;
1478
+
1479
+ const allTexts = extractMessageTexts(event.messages);
1480
+
1481
+ const userTurns = allTexts.filter((t) => t.role === "user").length;
1482
+ if (userTurns < config.captureMinTurns) {
1483
+ return;
1484
+ }
1485
+
1486
+ // Parse capture hints from all messages (Issue #81)
1487
+ const collectedHints: PalaiaHint[] = [];
1488
+ for (const t of allTexts) {
1489
+ const { hints } = parsePalaiaHints(t.text);
1490
+ collectedHints.push(...hints);
1491
+ }
1492
+
1493
+ // Only extract from recent exchanges — full history causes LLM timeouts
1494
+ // and dilutes extraction quality
1495
+ const recentTexts = trimToRecentExchanges(allTexts);
1496
+
1497
+ // Build exchange text from recent window only
1498
+ const exchangeParts: string[] = [];
1499
+ for (const t of recentTexts) {
1500
+ const { cleanedText } = parsePalaiaHints(t.text);
1501
+ exchangeParts.push(`[${t.role}]: ${cleanedText}`);
1502
+ }
1503
+ const exchangeText = exchangeParts.join("\n");
1504
+
1505
+ if (!shouldAttemptCapture(exchangeText)) {
1506
+ return;
1507
+ }
1508
+
1509
+ const knownProjects = await loadProjects(opts);
1510
+
1511
+ // Helper: build CLI args with metadata
1512
+ const buildWriteArgs = (
1513
+ content: string,
1514
+ type: string,
1515
+ tags: string[],
1516
+ itemProject?: string | null,
1517
+ itemScope?: string | null,
1518
+ ): string[] => {
1519
+ const args: string[] = [
1520
+ "write",
1521
+ content,
1522
+ "--type", type,
1523
+ "--tags", tags.join(",") || "auto-capture",
1524
+ ];
1525
+
1526
+ const scope = sanitizeScope(config.captureScope || itemScope, config.captureScope || "team");
1527
+ args.push("--scope", scope);
1528
+
1529
+ const project = config.captureProject || itemProject;
1530
+ if (project) {
1531
+ args.push("--project", project);
1532
+ }
1533
+
1534
+ if (agentName) {
1535
+ args.push("--agent", agentName);
1536
+ }
1537
+
1538
+ return args;
1539
+ };
1540
+
1541
+ // Helper: store LLM extraction results
1542
+ const storeLLMResults = async (results: ExtractionResult[]) => {
1543
+ for (const r of results) {
1544
+ if (r.significance >= config.captureMinSignificance) {
1545
+ const hintForProject = collectedHints.find((h) => h.project);
1546
+ const hintForScope = collectedHints.find((h) => h.scope);
1547
+
1548
+ const effectiveProject = hintForProject?.project || r.project;
1549
+ const effectiveScope = hintForScope?.scope || r.scope;
1550
+
1551
+ const args = buildWriteArgs(
1552
+ r.content,
1553
+ r.type,
1554
+ r.tags,
1555
+ effectiveProject,
1556
+ effectiveScope,
1557
+ );
1558
+ await run(args, { ...opts, timeoutMs: 10_000 });
1559
+ console.log(
1560
+ `[palaia] LLM auto-captured: type=${r.type}, significance=${r.significance}, tags=${r.tags.join(",")}, project=${effectiveProject || "none"}, scope=${effectiveScope || "team"}`
1561
+ );
1562
+ }
1563
+ }
1564
+ };
1565
+
1566
+ // LLM-based extraction (primary)
1567
+ let llmHandled = false;
1568
+ try {
1569
+ const results = await extractWithLLM(event.messages, api.config, {
1570
+ captureModel: config.captureModel,
1571
+ }, knownProjects);
1572
+
1573
+ await storeLLMResults(results);
1574
+ llmHandled = true;
1575
+ } catch (llmError) {
1576
+ // Check if this is a model-availability error (not a generic import failure)
1577
+ const errStr = String(llmError);
1578
+ const isModelError = /FailoverError|Unknown model|unknown model|401|403|model.*not found|not_found|model_not_found/i.test(errStr);
1579
+
1580
+ if (isModelError && config.captureModel) {
1581
+ // captureModel is broken — try primary model as fallback
1582
+ if (!_captureModelFailoverWarned) {
1583
+ _captureModelFailoverWarned = true;
1584
+ console.warn(`[palaia] WARNING: captureModel failed (${errStr}). Using primary model as fallback. Please update captureModel in your config.`);
1585
+ }
1586
+ try {
1587
+ // Retry without captureModel → resolveCaptureModel will use primary model
1588
+ const fallbackResults = await extractWithLLM(event.messages, api.config, {
1589
+ captureModel: undefined,
1590
+ }, knownProjects);
1591
+ await storeLLMResults(fallbackResults);
1592
+ llmHandled = true;
1593
+ } catch (fallbackError) {
1594
+ if (!_llmImportFailureLogged) {
1595
+ console.warn(`[palaia] LLM extraction failed (primary model fallback also failed): ${fallbackError}`);
1596
+ _llmImportFailureLogged = true;
1597
+ }
1598
+ }
1599
+ } else {
1600
+ if (!_llmImportFailureLogged) {
1601
+ console.warn(`[palaia] LLM extraction failed, using rule-based fallback: ${llmError}`);
1602
+ _llmImportFailureLogged = true;
1603
+ }
1604
+ }
1605
+ }
1606
+
1607
+ // Rule-based fallback
1608
+ if (!llmHandled) {
1609
+ let captureData: { tags: string[]; type: string; summary: string } | null = null;
1610
+
1611
+ if (config.captureFrequency === "significant") {
1612
+ const significance = extractSignificance(exchangeText);
1613
+ if (!significance) {
1614
+ return;
1615
+ }
1616
+ captureData = significance;
1617
+ } else {
1618
+ const summary = exchangeParts
1619
+ .slice(-4)
1620
+ .map((p) => p.slice(0, 200))
1621
+ .join(" | ")
1622
+ .slice(0, 500);
1623
+ captureData = { tags: ["auto-capture"], type: "memory", summary };
1624
+ }
1625
+
1626
+ const hintForProject = collectedHints.find((h) => h.project);
1627
+ const hintForScope = collectedHints.find((h) => h.scope);
1628
+
1629
+ const args = buildWriteArgs(
1630
+ captureData.summary,
1631
+ captureData.type,
1632
+ captureData.tags,
1633
+ hintForProject?.project,
1634
+ hintForScope?.scope,
1635
+ );
1636
+
1637
+ await run(args, { ...opts, timeoutMs: 10_000 });
1638
+ console.log(
1639
+ `[palaia] Rule-based auto-captured: type=${captureData.type}, tags=${captureData.tags.join(",")}`
1640
+ );
1641
+ }
1642
+
1643
+ // Mark that capture occurred in this turn
1644
+ if (sessionKey) {
1645
+ const turnState = getOrCreateTurnState(sessionKey);
1646
+ turnState.capturedInThisTurn = true;
1647
+ } else {
1648
+ }
1649
+ } catch (error) {
1650
+ console.warn(`[palaia] Auto-capture failed: ${error}`);
1651
+ }
1652
+
1653
+ // ── Emoji Reactions (Issue #87) ──────────────────────────
1654
+ // Send reactions AFTER capture completes, using turn state.
1655
+ if (sessionKey) {
1656
+ try {
1657
+ const turnState = turnStateBySession.get(sessionKey);
1658
+ if (turnState) {
1659
+ const provider = turnState.channelProvider
1660
+ || extractChannelFromSessionKey(sessionKey)
1661
+ || (ctx?.channelId as string | undefined);
1662
+ const channelId = turnState.lastInboundChannelId
1663
+ || extractChannelIdFromEvent(event, ctx)
1664
+ || extractSlackChannelIdFromSessionKey(sessionKey);
1665
+ const messageId = turnState.lastInboundMessageId;
1666
+
1667
+
1668
+ if (provider && REACTION_SUPPORTED_PROVIDERS.has(provider) && channelId && messageId) {
1669
+ // Capture confirmation: 💾
1670
+ if (turnState.capturedInThisTurn && config.showCaptureConfirm) {
1671
+ await sendReaction(channelId, messageId, "floppy_disk", provider);
1672
+ }
1673
+
1674
+ // Recall indicator: 🧠
1675
+ if (turnState.recallOccurred && config.showMemorySources) {
1676
+ await sendReaction(channelId, messageId, "brain", provider);
1677
+ }
1678
+ } else {
1679
+ }
1680
+ }
1681
+ } catch (reactionError) {
1682
+ console.warn(`[palaia] Reaction sending failed: ${reactionError}`);
1683
+ } finally {
1684
+ // Always clean up turn state
1685
+ deleteTurnState(sessionKey);
1686
+ }
1687
+ }
1688
+ });
1689
+ }
1690
+
1691
+ // ── agent_end: Recall-only reactions (when autoCapture is off) ─
1692
+ if (!config.autoCapture && config.showMemorySources) {
1693
+ api.on("agent_end", async (_event: any, ctx: any) => {
1694
+ const sessionKey = resolveSessionKeyFromCtx(ctx);
1695
+ if (!sessionKey) return;
1696
+
1697
+ try {
1698
+ const turnState = turnStateBySession.get(sessionKey);
1699
+ if (turnState?.recallOccurred) {
1700
+ const provider = turnState.channelProvider
1701
+ || extractChannelFromSessionKey(sessionKey);
1702
+ const channelId = turnState.lastInboundChannelId
1703
+ || extractChannelIdFromEvent(_event, ctx)
1704
+ || extractSlackChannelIdFromSessionKey(sessionKey);
1705
+ const messageId = turnState.lastInboundMessageId;
1706
+
1707
+ if (provider && REACTION_SUPPORTED_PROVIDERS.has(provider) && channelId && messageId) {
1708
+ await sendReaction(channelId, messageId, "brain", provider);
1709
+ }
1710
+ }
1711
+ } catch (err) {
1712
+ console.warn(`[palaia] Recall reaction failed: ${err}`);
1713
+ } finally {
1714
+ deleteTurnState(sessionKey);
1715
+ }
1716
+ });
1717
+ }
1718
+
84
1719
  // ── Startup Recovery Service ───────────────────────────────────
85
- // Replays pending WAL entries on plugin startup.
86
1720
  api.registerService({
87
1721
  id: "palaia-recovery",
88
1722
  start: async () => {