@causyne/agent 1.20.26 → 1.20.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +52 -4
  3. package/src/agentLoop.ts +48 -4
  4. package/src/browser/causyneBrowser.js +1 -1
  5. package/src/browser/causyneBrowser.ts +1 -1
  6. package/src/browser/searchProviders.js +1 -1
  7. package/src/browser/searchProviders.ts +1 -1
  8. package/src/decideTools.js +9 -1
  9. package/src/decideTools.ts +7 -1
  10. package/src/dynamicCatalogue.js +3 -1
  11. package/src/dynamicCatalogue.ts +3 -1
  12. package/src/launchIntent.js +1 -1
  13. package/src/launchIntent.ts +1 -1
  14. package/src/mcp/mcpRegistry.js +6 -2
  15. package/src/mcp/mcpRegistry.ts +5 -2
  16. package/src/memory/actrRanker.js +78 -0
  17. package/src/memory/actrRanker.ts +111 -0
  18. package/src/memory/contextBudget.js +131 -0
  19. package/src/memory/contextBudget.ts +155 -0
  20. package/src/memory/episodicStore.js +652 -0
  21. package/src/memory/episodicStore.ts +788 -0
  22. package/src/memory/episodicTypes.js +8 -0
  23. package/src/memory/episodicTypes.ts +124 -0
  24. package/src/memory/nearDuplicate.js +179 -0
  25. package/src/memory/nearDuplicate.ts +232 -0
  26. package/src/memory/symbolFolder.js +301 -0
  27. package/src/memory/symbolFolder.ts +327 -0
  28. package/src/toolPacks.js +1 -0
  29. package/src/toolPacks.ts +1 -0
  30. package/src/tools/desktopOpen.js +9 -2
  31. package/src/tools/desktopOpen.ts +8 -2
  32. package/src/tools/memoryRecall.js +211 -0
  33. package/src/tools/memoryRecall.ts +251 -0
  34. package/src/tools/nativeEngine.js +16 -2
  35. package/src/tools/nativeEngine.ts +16 -2
  36. package/src/tools/registry.js +2 -1
  37. package/src/tools/subagentOrchestrator.js +3 -2
  38. package/src/tools/toolSelfRepair.js +4 -1
  39. package/src/tools/toolSelfRepair.ts +4 -1
  40. package/src/toolsList.js +1 -0
  41. package/src/toolsList.ts +1 -0
@@ -0,0 +1,788 @@
1
+ /**
2
+ * @file src/memory/episodicStore.ts
3
+ * Causyne Sovereign Episodic Memory Store:
4
+ * - Zero-LLM deterministic tool observation compiler (`compileToolObservation`)
5
+ * - `<private>...</private>` tag stripping and credential redaction (`redactPrivateAndSecrets`)
6
+ * - 2-Tier IDF-Veto near-duplicate merging with ACT-R reinforcement (`recordObservation`)
7
+ * - 3-Layer Progressive Memory Disclosure (`searchIndex`, `getTimelineWindow`, `getObservationsByIds`)
8
+ * - ACT-R strength-ranked startup context builder with `fitEpisodicContextToBudget`
9
+ * - Auto-detection bridge for external SQLite memory archives (`~/.causyne/memory-archive.db`)
10
+ *
11
+ * Authorship: Strict TypeScript (Causyne Agent).
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+ import { execFileSync } from 'node:child_process';
18
+ import { causyneHome } from '../utils/paths.js';
19
+ import { computeObservationStrength, rankObservationsByStrength } from './actrRanker.js';
20
+ import { DEFAULT_EPISODIC_BUDGET_CHARS, fitEpisodicContextToBudget } from './contextBudget.js';
21
+ import { buildCorpusIdfMap, decideNearDuplicate, tokenizeForDedup } from './nearDuplicate.js';
22
+ import type {
23
+ EpisodicObservation,
24
+ EpisodicSessionSummary,
25
+ ObservationBatchResult,
26
+ ObservationType,
27
+ ProgressiveSearchResult,
28
+ ProgressiveSearchRow,
29
+ TimelineWindowItem,
30
+ TimelineWindowResult
31
+ } from './episodicTypes.js';
32
+
33
+ export const PROGRESSIVE_MAX_BYTES = 64 * 1024;
34
+ const MAX_OBSERVATIONS_PER_PROJECT = 400;
35
+ const MAX_SUMMARIES_PER_PROJECT = 80;
36
+ const MAX_REINFORCEMENT_TIMESTAMPS = 32;
37
+
38
+ interface PersistedEpisodicData {
39
+ schemaVersion: number;
40
+ nextObservationId: number;
41
+ nextSummaryId: number;
42
+ observations: EpisodicObservation[];
43
+ summaries: EpisodicSessionSummary[];
44
+ }
45
+
46
+ export interface RecordObservationInput {
47
+ readonly taskId: string;
48
+ readonly workspace: string;
49
+ readonly type: ObservationType;
50
+ readonly title: string;
51
+ readonly subtitle?: string | undefined;
52
+ readonly narrative: string;
53
+ readonly facts?: readonly string[] | undefined;
54
+ readonly concepts?: readonly string[] | undefined;
55
+ readonly filesRead?: readonly string[] | undefined;
56
+ readonly filesModified?: readonly string[] | undefined;
57
+ readonly toolName: string;
58
+ readonly createdAtEpochMs?: number | undefined;
59
+ readonly source?: 'native' | 'external_bridge' | undefined;
60
+ }
61
+
62
+ export interface SearchEpisodicOptions {
63
+ readonly query?: string | undefined;
64
+ readonly workspace?: string | undefined;
65
+ readonly project?: string | undefined;
66
+ readonly type?: ObservationType | 'summary' | undefined;
67
+ readonly limit?: number | undefined;
68
+ readonly workspaceOnly?: boolean | undefined;
69
+ readonly nowMs?: number | undefined;
70
+ }
71
+
72
+ export interface TimelineQueryOptions {
73
+ readonly anchorId: string | number;
74
+ readonly workspace?: string | undefined;
75
+ readonly depthBefore?: number | undefined;
76
+ readonly depthAfter?: number | undefined;
77
+ }
78
+
79
+ /**
80
+ * Strip `<private>...</private>` tags and redact API keys, bearer tokens, and secrets.
81
+ */
82
+ export function redactPrivateAndSecrets(input: string): string {
83
+ if (!input) return '';
84
+ return String(input)
85
+ .replace(/<private>[\s\S]*?<\/private>/gi, '[REDACTED_PRIVATE]')
86
+ .replace(/\b(sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_-]{25,})\b/g, '[REDACTED_KEY]')
87
+ .replace(/(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi, '$1[REDACTED_TOKEN]')
88
+ .replace(/((?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?)[^\s"',;]{8,}/gi, '$1[REDACTED]')
89
+ .trim();
90
+ }
91
+
92
+ /**
93
+ * Derive a clean project name from a workspace path.
94
+ */
95
+ export function projectFromWorkspace(workspace: string): string {
96
+ const trimmed = String(workspace || '').trim();
97
+ if (!trimmed) return 'default';
98
+ const base = path.basename(path.resolve(trimmed));
99
+ return base || 'default';
100
+ }
101
+
102
+ const LOW_SIGNAL_READ_TOOLS: ReadonlySet<string> = new Set([
103
+ 'fs_list', 'fs_find', 'process_list', 'check_system_specs', 'tool_search'
104
+ ]);
105
+
106
+ /**
107
+ * Deterministically compile a completed tool execution into a structured observation input,
108
+ * or return `null` if the tool call is low-signal noise that should not clutter memory.
109
+ */
110
+ export function compileToolObservation(params: {
111
+ taskId: string;
112
+ workspace: string;
113
+ toolName: string;
114
+ args: Record<string, unknown>;
115
+ result: Record<string, unknown> | null | undefined;
116
+ nowMs?: number | undefined;
117
+ }): RecordObservationInput | null {
118
+ const { taskId, workspace, toolName, args, result } = params;
119
+ const normalizedTool = String(toolName || '').trim();
120
+ if (!normalizedTool || LOW_SIGNAL_READ_TOOLS.has(normalizedTool)) {
121
+ return null;
122
+ }
123
+
124
+ const isSuccess = result ? (result.success !== false && !result.error) : true;
125
+ if (!isSuccess) {
126
+ // Only record failed verification or build commands as bugfix discoveries; skip transient tool errors
127
+ const cmd = typeof args.command === 'string' ? args.command : typeof args.cmd === 'string' ? args.cmd : '';
128
+ if (!cmd || !/\b(test|build|tsc|typecheck|lint|pytest|cargo)\b/i.test(cmd)) {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ const rawPath = String(
134
+ args.path ?? args.file_path ?? args.filePath ?? args.target ?? ''
135
+ ).trim();
136
+ const rawRel = rawPath && workspace
137
+ ? (path.isAbsolute(rawPath) ? path.relative(workspace, rawPath) : rawPath)
138
+ : rawPath;
139
+ const relPath = rawRel ? rawRel.replace(/\\/g, '/') : '';
140
+
141
+ const lowerTool = normalizedTool.toLowerCase();
142
+
143
+ // 1. File mutations (fs_write, fs_edit, MultiEdit, write_file, edit_file)
144
+ if (['fs_write', 'fs_edit', 'multiedit', 'write_file', 'edit_file', 'replace_file_content', 'write', 'edit'].includes(lowerTool)) {
145
+ if (!relPath) return null;
146
+ const isNewWrite = lowerTool === 'fs_write' || lowerTool === 'write_file' || lowerTool === 'write';
147
+ const type: ObservationType = isNewWrite
148
+ ? 'feature'
149
+ : /\b(fix|bug|patch|error|repair)\b/i.test(String(args.Replacement ?? args.content ?? ''))
150
+ ? 'bugfix'
151
+ : 'refactor';
152
+ const actionVerb = isNewWrite ? 'Authored' : 'Updated';
153
+ const snippetSource = String(args.Replacement ?? args.content ?? '').slice(0, 320);
154
+ const cleanSnippet = redactPrivateAndSecrets(snippetSource).replace(/\s+/g, ' ').trim();
155
+ return {
156
+ taskId,
157
+ workspace,
158
+ type,
159
+ title: `${actionVerb} ${relPath}`,
160
+ subtitle: `${normalizedTool} on ${relPath}`,
161
+ narrative: cleanSnippet
162
+ ? `${actionVerb} file ${relPath} via ${normalizedTool}. Key content: ${cleanSnippet.slice(0, 220)}`
163
+ : `${actionVerb} file ${relPath} via ${normalizedTool}.`,
164
+ facts: [`Modified ${relPath}`],
165
+ concepts: [type, path.extname(relPath).replace(/^\./, '') || 'file'],
166
+ filesRead: [],
167
+ filesModified: [relPath],
168
+ toolName: normalizedTool,
169
+ ...(params.nowMs !== undefined ? { createdAtEpochMs: params.nowMs } : {})
170
+ };
171
+ }
172
+
173
+ // 2. Shell & Verification commands (sysRun, bash, run_command)
174
+ if (['sysrun', 'bash', 'run_command', 'execute', 'terminal_persistent_shell'].includes(lowerTool)) {
175
+ const command = redactPrivateAndSecrets(
176
+ String(args.command ?? args.cmd ?? '').trim()
177
+ );
178
+ if (!command) return null;
179
+ // Skip read-only shell probes and ad-hoc inspection one-liners so episodic memory stays high-signal
180
+ if (/^(?:ls|pwd|cd|cat|head|tail|echo|which|true|find|wc|grep|egrep|fgrep|rg|sed|awk|jq|stat|file|nl|sort|uniq|cut|tr)\b/i.test(command)) {
181
+ return null;
182
+ }
183
+ if (/^(?:node\s+-e|python3?\s+-c|git\s+(?:status|log|diff|show|branch|rev-parse))\b/i.test(command)) {
184
+ return null;
185
+ }
186
+ const isVerify = /\b(test|build|tsc|typecheck|lint|pytest|cargo|go\s+test|check|vitest|jest|gradle)\b/i.test(command);
187
+ const isHighSignalAction = isVerify || /\b(install|commit|deploy|migrate|publish|docker|rsync|cmake|make)\b/i.test(command);
188
+ if (!isHighSignalAction) {
189
+ return null;
190
+ }
191
+ const type: ObservationType = isVerify ? 'verification' : 'discovery';
192
+ const statusWord = isSuccess ? 'Succeeded' : 'Failed';
193
+ const outputPreview = redactPrivateAndSecrets(
194
+ String(result?.output ?? result?.stdout ?? result?.error ?? '').slice(0, 240)
195
+ ).replace(/\s+/g, ' ').trim();
196
+ return {
197
+ taskId,
198
+ workspace,
199
+ type,
200
+ title: `${statusWord}: ${command.slice(0, 80)}`,
201
+ subtitle: `${normalizedTool} (${statusWord.toLowerCase()})`,
202
+ narrative: outputPreview
203
+ ? `Command \`${command.slice(0, 120)}\` ${statusWord.toLowerCase()}: ${outputPreview}`
204
+ : `Command \`${command.slice(0, 120)}\` ${statusWord.toLowerCase()}.`,
205
+ facts: [`Command: ${command.slice(0, 100)} (${statusWord.toLowerCase()})`],
206
+ concepts: [type, 'command'],
207
+ filesRead: [],
208
+ filesModified: [],
209
+ toolName: normalizedTool,
210
+ ...(params.nowMs !== undefined ? { createdAtEpochMs: params.nowMs } : {})
211
+ };
212
+ }
213
+
214
+ // 3. Browser / Visual Verification
215
+ if (['browser_act', 'screenshot', 'vision_inspect_ui'].includes(lowerTool)) {
216
+ const action = String(args.action ?? 'verify').trim();
217
+ return {
218
+ taskId,
219
+ workspace,
220
+ type: 'verification',
221
+ title: `Verified UI via ${normalizedTool} (${action})`,
222
+ subtitle: `${normalizedTool} ${action}`,
223
+ narrative: `Executed UI/browser verification step using ${normalizedTool} (${action}).`,
224
+ facts: [`Verified UI with ${normalizedTool}`],
225
+ concepts: ['verification', 'ui'],
226
+ filesRead: relPath ? [relPath] : [],
227
+ filesModified: [],
228
+ toolName: normalizedTool,
229
+ ...(params.nowMs !== undefined ? { createdAtEpochMs: params.nowMs } : {})
230
+ };
231
+ }
232
+
233
+ // 4. Architecture Decisions & Explicit Memory Writes
234
+ if (lowerTool === 'request_decision' || lowerTool === 'memory_write') {
235
+ const text = redactPrivateAndSecrets(
236
+ String(args.fact ?? args.question ?? args.header ?? '').trim()
237
+ );
238
+ if (!text) return null;
239
+ return {
240
+ taskId,
241
+ workspace,
242
+ type: 'decision',
243
+ title: `Decision: ${text.slice(0, 90)}`,
244
+ subtitle: normalizedTool,
245
+ narrative: text.slice(0, 320),
246
+ facts: [text.slice(0, 180)],
247
+ concepts: ['decision', 'architecture'],
248
+ filesRead: [],
249
+ filesModified: [],
250
+ toolName: normalizedTool,
251
+ ...(params.nowMs !== undefined ? { createdAtEpochMs: params.nowMs } : {})
252
+ };
253
+ }
254
+
255
+ return null;
256
+ }
257
+
258
+ export class EpisodicMemoryStore {
259
+ private readonly storePath: string;
260
+ private data: PersistedEpisodicData | null = null;
261
+ private externalBridgeImported = false;
262
+ private static defaultInstance: EpisodicMemoryStore | null = null;
263
+
264
+ constructor(customStorePath?: string) {
265
+ this.storePath = customStorePath
266
+ ? path.resolve(customStorePath)
267
+ : path.join(causyneHome(), 'episodic-memory.json');
268
+ }
269
+
270
+ static getInstance(): EpisodicMemoryStore {
271
+ if (!EpisodicMemoryStore.defaultInstance) {
272
+ EpisodicMemoryStore.defaultInstance = new EpisodicMemoryStore();
273
+ }
274
+ return EpisodicMemoryStore.defaultInstance;
275
+ }
276
+
277
+ private ensureLoaded(): PersistedEpisodicData {
278
+ if (this.data) return this.data;
279
+ try {
280
+ if (fs.existsSync(this.storePath)) {
281
+ const raw = JSON.parse(fs.readFileSync(this.storePath, 'utf8')) as Partial<PersistedEpisodicData>;
282
+ if (raw && Array.isArray(raw.observations) && Array.isArray(raw.summaries)) {
283
+ const cleanedObservations = raw.observations.filter((obs) => {
284
+ if (obs.type !== 'discovery') return true;
285
+ return !/^(?:Succeeded|Failed):\s*(?:find|wc|grep|egrep|fgrep|rg|sed|awk|jq|stat|file|ls|cat|head|tail|node\s+-e|python3?\s+-c)\b/i.test(obs.title);
286
+ });
287
+ this.data = {
288
+ schemaVersion: 1,
289
+ nextObservationId: typeof raw.nextObservationId === 'number' ? raw.nextObservationId : (raw.observations.length + 1),
290
+ nextSummaryId: typeof raw.nextSummaryId === 'number' ? raw.nextSummaryId : (raw.summaries.length + 1),
291
+ observations: cleanedObservations,
292
+ summaries: raw.summaries
293
+ };
294
+ if (cleanedObservations.length !== raw.observations.length) {
295
+ this.save();
296
+ }
297
+ return this.data;
298
+ }
299
+ }
300
+ } catch {
301
+ // Fallback to fresh store if corrupted
302
+ }
303
+ this.data = {
304
+ schemaVersion: 1,
305
+ nextObservationId: 1,
306
+ nextSummaryId: 1,
307
+ observations: [],
308
+ summaries: []
309
+ };
310
+ return this.data;
311
+ }
312
+
313
+ private save(): void {
314
+ if (!this.data) return;
315
+ try {
316
+ const dir = path.dirname(this.storePath);
317
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
318
+ const tmpPath = `${this.storePath}.tmp.${process.pid}`;
319
+ fs.writeFileSync(tmpPath, JSON.stringify(this.data, null, 2), { encoding: 'utf8', mode: 0o600 });
320
+ fs.renameSync(tmpPath, this.storePath);
321
+ } catch {
322
+ // Fail-open so memory persistence never crashes an active task
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Record a new observation or reinforce an existing near-duplicate observation
328
+ * using 2-Tier IDF-Veto deduplication.
329
+ */
330
+ recordObservation(input: RecordObservationInput): {
331
+ observation: EpisodicObservation;
332
+ dedupTier: 'exact' | 'candidate' | 'distinct';
333
+ reinforcedId?: number | undefined;
334
+ } {
335
+ const store = this.ensureLoaded();
336
+ const nowMs = input.createdAtEpochMs ?? Date.now();
337
+ const project = projectFromWorkspace(input.workspace);
338
+
339
+ const cleanTitle = redactPrivateAndSecrets(input.title).slice(0, 160);
340
+ const cleanSubtitle = redactPrivateAndSecrets(input.subtitle ?? '').slice(0, 160);
341
+ const cleanNarrative = redactPrivateAndSecrets(input.narrative).slice(0, 1200);
342
+ const cleanFacts = (input.facts ?? []).map((f) => redactPrivateAndSecrets(f).slice(0, 200)).filter(Boolean);
343
+ const cleanConcepts = (input.concepts ?? []).map((c) => redactPrivateAndSecrets(c).slice(0, 60)).filter(Boolean);
344
+ const filesRead = [...new Set((input.filesRead ?? []).map((f) => String(f).trim()).filter(Boolean))].slice(0, 16);
345
+ const filesModified = [...new Set((input.filesModified ?? []).map((f) => String(f).trim()).filter(Boolean))].slice(0, 16);
346
+
347
+ const projectPool = store.observations.filter((o) => o.project === project);
348
+ const idfMap = buildCorpusIdfMap(projectPool);
349
+
350
+ // Check recent observations in the same project for Tier-0 or Tier-1 match
351
+ for (let i = projectPool.length - 1; i >= Math.max(0, projectPool.length - 80); i--) {
352
+ const existing = projectPool[i];
353
+ if (!existing) continue;
354
+ const decision = decideNearDuplicate(
355
+ { title: cleanTitle, narrative: cleanNarrative },
356
+ { title: existing.title, narrative: existing.narrative },
357
+ idfMap,
358
+ projectPool.length
359
+ );
360
+ if (decision.tier === 'exact' || decision.tier === 'candidate') {
361
+ const nextReinforced = [...existing.reinforcedAtEpochsMs, nowMs].slice(-MAX_REINFORCEMENT_TIMESTAMPS);
362
+ const updated: EpisodicObservation = {
363
+ ...existing,
364
+ reinforcedAtEpochsMs: nextReinforced,
365
+ reinforcementCount: existing.reinforcementCount + 1,
366
+ filesRead: [...new Set([...existing.filesRead, ...filesRead])].slice(0, 16),
367
+ filesModified: [...new Set([...existing.filesModified, ...filesModified])].slice(0, 16),
368
+ facts: [...new Set([...existing.facts, ...cleanFacts])].slice(0, 12)
369
+ };
370
+ const idx = store.observations.findIndex((o) => o.id === existing.id);
371
+ if (idx >= 0) {
372
+ store.observations[idx] = updated;
373
+ this.save();
374
+ }
375
+ return {
376
+ observation: updated,
377
+ dedupTier: decision.tier,
378
+ reinforcedId: updated.id
379
+ };
380
+ }
381
+ }
382
+
383
+ const created: EpisodicObservation = {
384
+ id: store.nextObservationId++,
385
+ taskId: input.taskId,
386
+ workspace: input.workspace,
387
+ project,
388
+ type: input.type,
389
+ title: cleanTitle,
390
+ subtitle: cleanSubtitle,
391
+ narrative: cleanNarrative,
392
+ facts: cleanFacts,
393
+ concepts: cleanConcepts,
394
+ filesRead,
395
+ filesModified,
396
+ toolName: input.toolName,
397
+ createdAtEpochMs: nowMs,
398
+ reinforcedAtEpochsMs: [],
399
+ reinforcementCount: 0,
400
+ source: input.source ?? 'native'
401
+ };
402
+
403
+ store.observations.push(created);
404
+ this.enforceProjectCap(project);
405
+ this.save();
406
+
407
+ return {
408
+ observation: created,
409
+ dedupTier: 'distinct'
410
+ };
411
+ }
412
+
413
+ /**
414
+ * Record a structured session checkpoint summary.
415
+ */
416
+ recordSessionSummary(input: {
417
+ taskId: string;
418
+ workspace: string;
419
+ request: string;
420
+ investigated?: string | undefined;
421
+ learned?: string | undefined;
422
+ completed: string;
423
+ nextSteps?: string | undefined;
424
+ createdAtEpochMs?: number | undefined;
425
+ }): EpisodicSessionSummary {
426
+ const store = this.ensureLoaded();
427
+ const project = projectFromWorkspace(input.workspace);
428
+ const summary: EpisodicSessionSummary = {
429
+ id: store.nextSummaryId++,
430
+ taskId: input.taskId,
431
+ workspace: input.workspace,
432
+ project,
433
+ request: redactPrivateAndSecrets(input.request).slice(0, 300),
434
+ investigated: redactPrivateAndSecrets(input.investigated ?? '').slice(0, 300),
435
+ learned: redactPrivateAndSecrets(input.learned ?? '').slice(0, 300),
436
+ completed: redactPrivateAndSecrets(input.completed).slice(0, 400),
437
+ nextSteps: redactPrivateAndSecrets(input.nextSteps ?? '').slice(0, 240),
438
+ createdAtEpochMs: input.createdAtEpochMs ?? Date.now()
439
+ };
440
+ store.summaries.push(summary);
441
+ const projectSummaries = store.summaries.filter((s) => s.project === project);
442
+ if (projectSummaries.length > MAX_SUMMARIES_PER_PROJECT) {
443
+ const oldestId = projectSummaries[0]?.id;
444
+ if (oldestId !== undefined) {
445
+ store.summaries = store.summaries.filter((s) => s.id !== oldestId);
446
+ }
447
+ }
448
+ this.save();
449
+ return summary;
450
+ }
451
+
452
+ private enforceProjectCap(project: string): void {
453
+ const store = this.ensureLoaded();
454
+ const projectObs = store.observations.filter((o) => o.project === project);
455
+ if (projectObs.length <= MAX_OBSERVATIONS_PER_PROJECT) return;
456
+
457
+ // Retain top MAX_OBSERVATIONS_PER_PROJECT using ACT-R strength ranking so reinforced memories survive eviction
458
+ const surviving = new Set(
459
+ rankObservationsByStrength(projectObs, MAX_OBSERVATIONS_PER_PROJECT).map((o) => o.id)
460
+ );
461
+ store.observations = store.observations.filter(
462
+ (o) => o.project !== project || surviving.has(o.id)
463
+ );
464
+ }
465
+
466
+ /**
467
+ * Layer 1 of Progressive Disclosure (`search`):
468
+ * Returns a compact index of observations and session summaries matching `query`,
469
+ * ranked by query term overlap + ACT-R cognitive strength.
470
+ */
471
+ searchIndex(options: SearchEpisodicOptions = {}): ProgressiveSearchResult {
472
+ const store = this.ensureLoaded();
473
+ const nowMs = options.nowMs ?? Date.now();
474
+ const limit = Math.max(1, Math.min(50, options.limit ?? 15));
475
+ const query = String(options.query ?? '').trim();
476
+ const queryTokens = tokenizeForDedup(query);
477
+ const targetProject = options.project
478
+ ? options.project
479
+ : options.workspace
480
+ ? projectFromWorkspace(options.workspace)
481
+ : '';
482
+
483
+ const rows: ProgressiveSearchRow[] = [];
484
+
485
+ for (const obs of store.observations) {
486
+ if (options.workspaceOnly && targetProject && obs.project !== targetProject) continue;
487
+ if (options.type && options.type !== 'summary' && obs.type !== options.type) continue;
488
+
489
+ const haystack = `${obs.title} ${obs.subtitle} ${obs.narrative} ${obs.facts.join(' ')} ${obs.filesModified.join(' ')} ${obs.filesRead.join(' ')}`.toLowerCase();
490
+ let termHits = 0;
491
+ if (queryTokens.length > 0) {
492
+ for (const qt of queryTokens) {
493
+ if (haystack.includes(qt)) termHits += 1;
494
+ }
495
+ if (termHits === 0 && !haystack.includes(query.toLowerCase())) continue;
496
+ }
497
+
498
+ const actr = computeObservationStrength(obs.createdAtEpochMs, obs.reinforcedAtEpochsMs, nowMs);
499
+ const projectBoost = targetProject && obs.project === targetProject ? 0.5 : 0;
500
+ const score = termHits * 2.0 + actr + projectBoost;
501
+
502
+ rows.push({
503
+ id: `#${obs.id}`,
504
+ numericId: obs.id,
505
+ kind: 'observation',
506
+ type: obs.type,
507
+ project: obs.project,
508
+ title: obs.title,
509
+ subtitle: obs.subtitle || obs.toolName,
510
+ createdAtEpochMs: obs.createdAtEpochMs,
511
+ reinforcementCount: obs.reinforcementCount,
512
+ score: Number(score.toFixed(4))
513
+ });
514
+ }
515
+
516
+ if (!options.type || options.type === 'summary') {
517
+ for (const sum of store.summaries) {
518
+ if (options.workspaceOnly && targetProject && sum.project !== targetProject) continue;
519
+ const haystack = `${sum.request} ${sum.learned} ${sum.completed} ${sum.nextSteps}`.toLowerCase();
520
+ let termHits = 0;
521
+ if (queryTokens.length > 0) {
522
+ for (const qt of queryTokens) {
523
+ if (haystack.includes(qt)) termHits += 1;
524
+ }
525
+ if (termHits === 0 && !haystack.includes(query.toLowerCase())) continue;
526
+ }
527
+ const actr = computeObservationStrength(sum.createdAtEpochMs, [], nowMs);
528
+ const projectBoost = targetProject && sum.project === targetProject ? 0.5 : 0;
529
+ const score = termHits * 2.0 + actr + projectBoost;
530
+
531
+ rows.push({
532
+ id: `S#${sum.id}`,
533
+ numericId: sum.id,
534
+ kind: 'summary',
535
+ type: 'summary',
536
+ project: sum.project,
537
+ title: sum.request.slice(0, 120),
538
+ subtitle: sum.completed.slice(0, 120),
539
+ createdAtEpochMs: sum.createdAtEpochMs,
540
+ reinforcementCount: 0,
541
+ score: Number(score.toFixed(4))
542
+ });
543
+ }
544
+ }
545
+
546
+ rows.sort((a, b) => {
547
+ if (b.score !== a.score) return b.score - a.score;
548
+ return b.createdAtEpochMs - a.createdAtEpochMs;
549
+ });
550
+
551
+ return {
552
+ query,
553
+ totalMatches: rows.length,
554
+ results: rows.slice(0, limit)
555
+ };
556
+ }
557
+
558
+ /**
559
+ * Layer 2 of Progressive Disclosure (`timeline`):
560
+ * Returns a chronological window (`depthBefore`, `depthAfter`) around an anchor observation ID.
561
+ */
562
+ getTimelineWindow(options: TimelineQueryOptions): TimelineWindowResult {
563
+ const store = this.ensureLoaded();
564
+ const rawId = String(options.anchorId).replace(/^[#S]+/i, '').trim();
565
+ const numericAnchor = Number.parseInt(rawId, 10);
566
+ const depthBefore = Math.max(1, Math.min(20, options.depthBefore ?? 5));
567
+ const depthAfter = Math.max(1, Math.min(20, options.depthAfter ?? 5));
568
+
569
+ const targetObs = store.observations.find((o) => o.id === numericAnchor);
570
+ if (!targetObs) {
571
+ return {
572
+ anchorId: `#${rawId}`,
573
+ project: options.workspace ? projectFromWorkspace(options.workspace) : 'default',
574
+ before: [],
575
+ anchor: null,
576
+ after: []
577
+ };
578
+ }
579
+
580
+ const projectChronological = store.observations
581
+ .filter((o) => o.project === targetObs.project)
582
+ .sort((a, b) => a.createdAtEpochMs - b.createdAtEpochMs || a.id - b.id);
583
+
584
+ const anchorIdx = projectChronological.findIndex((o) => o.id === targetObs.id);
585
+ const toItem = (o: EpisodicObservation, isAnchor: boolean): TimelineWindowItem => ({
586
+ id: `#${o.id}`,
587
+ numericId: o.id,
588
+ isAnchor,
589
+ type: o.type,
590
+ title: o.title,
591
+ subtitle: o.subtitle,
592
+ toolName: o.toolName,
593
+ filesModified: o.filesModified,
594
+ createdAtEpochMs: o.createdAtEpochMs
595
+ });
596
+
597
+ const beforeSlice = projectChronological.slice(Math.max(0, anchorIdx - depthBefore), anchorIdx);
598
+ const afterSlice = projectChronological.slice(anchorIdx + 1, anchorIdx + 1 + depthAfter);
599
+
600
+ return {
601
+ anchorId: `#${targetObs.id}`,
602
+ project: targetObs.project,
603
+ before: beforeSlice.map((o) => toItem(o, false)),
604
+ anchor: toItem(targetObs, true),
605
+ after: afterSlice.map((o) => toItem(o, false))
606
+ };
607
+ }
608
+
609
+ /**
610
+ * Layer 3 of Progressive Disclosure (`get_observations`):
611
+ * Fetches full observation details for specific IDs, bounded by `PROGRESSIVE_MAX_BYTES` (64 KB).
612
+ * Also reinforces fetched observations via ACT-R since active retrieval indicates utility.
613
+ */
614
+ getObservationsByIds(
615
+ ids: readonly (string | number)[],
616
+ maxBytes: number = PROGRESSIVE_MAX_BYTES
617
+ ): ObservationBatchResult {
618
+ const store = this.ensureLoaded();
619
+ const requestedIds = ids.map((id) => String(id).trim()).filter(Boolean);
620
+ const observations: EpisodicObservation[] = [];
621
+ const omittedIds: string[] = [];
622
+ let totalBytes = 0;
623
+ let truncatedByByteLimit = false;
624
+ const nowMs = Date.now();
625
+ let dirty = false;
626
+
627
+ for (const raw of requestedIds) {
628
+ const numId = Number.parseInt(raw.replace(/^[#S]+/i, ''), 10);
629
+ if (!Number.isFinite(numId)) continue;
630
+ const idx = store.observations.findIndex((o) => o.id === numId);
631
+ if (idx < 0) continue;
632
+ const obs = store.observations[idx];
633
+ if (!obs) continue;
634
+
635
+ const serialized = JSON.stringify(obs);
636
+ const byteLen = Buffer.byteLength(serialized, 'utf8');
637
+ if (observations.length > 0 && totalBytes + byteLen > maxBytes) {
638
+ truncatedByByteLimit = true;
639
+ omittedIds.push(`#${obs.id}`);
640
+ continue;
641
+ }
642
+
643
+ totalBytes += byteLen;
644
+ observations.push(obs);
645
+
646
+ // Reinforce retrieved memory in ACT-R
647
+ const reinforced = [...obs.reinforcedAtEpochsMs, nowMs].slice(-MAX_REINFORCEMENT_TIMESTAMPS);
648
+ store.observations[idx] = {
649
+ ...obs,
650
+ reinforcedAtEpochsMs: reinforced,
651
+ reinforcementCount: obs.reinforcementCount + 1
652
+ };
653
+ dirty = true;
654
+ }
655
+
656
+ if (dirty) {
657
+ this.save();
658
+ }
659
+
660
+ return {
661
+ requestedIds,
662
+ observations,
663
+ omittedIds,
664
+ truncatedByByteLimit,
665
+ totalBytes
666
+ };
667
+ }
668
+
669
+ /**
670
+ * Build the ACT-R ranked, character-budgeted startup context for `AgentLoop.buildStaticContext()`.
671
+ */
672
+ buildStartupEpisodicContext(
673
+ workspace: string,
674
+ maxChars: number = DEFAULT_EPISODIC_BUDGET_CHARS,
675
+ nowMs: number = Date.now()
676
+ ): string {
677
+ this.autoSyncExternalBridgeOnce(workspace);
678
+ const store = this.ensureLoaded();
679
+ const project = projectFromWorkspace(workspace);
680
+ const projectObservations = store.observations.filter((o) => o.project === project);
681
+ const projectSummaries = store.summaries
682
+ .filter((s) => s.project === project)
683
+ .sort((a, b) => b.createdAtEpochMs - a.createdAtEpochMs)
684
+ .slice(0, 5);
685
+
686
+ if (projectObservations.length === 0 && projectSummaries.length === 0) {
687
+ return '';
688
+ }
689
+
690
+ const ranked = rankObservationsByStrength(projectObservations, 16, nowMs);
691
+ // Expand full narratives for top 3 highest-priority observations initially;
692
+ // `fitEpisodicContextToBudget` will automatically shed them if over budget.
693
+ const fullObservationIds = new Set<number>(ranked.slice(0, 3).map((o) => o.id));
694
+
695
+ return fitEpisodicContextToBudget(
696
+ {
697
+ project,
698
+ observations: ranked,
699
+ summaries: projectSummaries,
700
+ fullObservationIds,
701
+ showLastSummaryDetails: true
702
+ },
703
+ maxChars
704
+ );
705
+ }
706
+
707
+ /**
708
+ * Auto-detect if a local SQLite episodic archive exists in `~/.causyne/memory-archive.db`
709
+ * (or `CAUSYNE_MEMORY_ARCHIVE_DB`) and optionally import recent observations for the current project.
710
+ */
711
+ detectExternalMemoryStore(): { available: boolean; dbPath: string } {
712
+ const envPath = process.env.CAUSYNE_MEMORY_ARCHIVE_DB?.trim();
713
+ const candidate = envPath
714
+ ? path.resolve(envPath)
715
+ : path.join(causyneHome(), 'memory-archive.db');
716
+ try {
717
+ const stat = fs.statSync(candidate);
718
+ return { available: stat.isFile() && stat.size > 0, dbPath: candidate };
719
+ } catch {
720
+ return { available: false, dbPath: candidate };
721
+ }
722
+ }
723
+
724
+ autoSyncExternalBridgeOnce(workspace: string): number {
725
+ if (this.externalBridgeImported) return 0;
726
+ this.externalBridgeImported = true;
727
+ const ext = this.detectExternalMemoryStore();
728
+ if (!ext.available) return 0;
729
+
730
+ const project = projectFromWorkspace(workspace);
731
+ try {
732
+ const sql = `SELECT title, subtitle, narrative, type, created_at_epoch FROM observations WHERE project = '${project.replace(/'/g, "''")}' ORDER BY created_at_epoch DESC LIMIT 20;`;
733
+ const raw = execFileSync('sqlite3', ['-json', ext.dbPath, sql], {
734
+ encoding: 'utf8',
735
+ timeout: 1500,
736
+ stdio: ['ignore', 'pipe', 'ignore']
737
+ }).trim();
738
+ if (!raw) return 0;
739
+ const rows = JSON.parse(raw) as Array<Record<string, unknown>>;
740
+ let imported = 0;
741
+ for (const row of rows) {
742
+ const title = typeof row.title === 'string' ? row.title : '';
743
+ const narrative = typeof row.narrative === 'string' ? row.narrative : '';
744
+ if (!title) continue;
745
+ const res = this.recordObservation({
746
+ taskId: 'external_bridge',
747
+ workspace,
748
+ type: 'discovery',
749
+ title,
750
+ subtitle: typeof row.subtitle === 'string' ? row.subtitle : 'external',
751
+ narrative,
752
+ toolName: 'external_bridge',
753
+ createdAtEpochMs: typeof row.created_at_epoch === 'number' ? row.created_at_epoch : Date.now(),
754
+ source: 'external_bridge'
755
+ });
756
+ if (res.dedupTier === 'distinct') imported += 1;
757
+ }
758
+ return imported;
759
+ } catch {
760
+ return 0;
761
+ }
762
+ }
763
+
764
+ getStats(workspace?: string): {
765
+ totalObservations: number;
766
+ totalSummaries: number;
767
+ projectObservations: number;
768
+ externalStoreAvailable: boolean;
769
+ externalStorePath: string;
770
+ } {
771
+ const store = this.ensureLoaded();
772
+ const project = workspace ? projectFromWorkspace(workspace) : '';
773
+ const projectObservations = project
774
+ ? store.observations.filter((o) => o.project === project).length
775
+ : store.observations.length;
776
+ const ext = this.detectExternalMemoryStore();
777
+ return {
778
+ totalObservations: store.observations.length,
779
+ totalSummaries: store.summaries.length,
780
+ projectObservations,
781
+ externalStoreAvailable: ext.available,
782
+ externalStorePath: ext.dbPath
783
+ };
784
+ }
785
+ }
786
+
787
+ export const episodicStore = EpisodicMemoryStore.getInstance();
788
+