@causyne/agent 1.20.25 → 1.20.28

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