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