@causyne/agent 1.20.55 → 1.20.62
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/acp/agentCatalog.js +1 -1
- package/src/acp/agentCatalog.ts +1 -1
- package/src/acp/peerProfiles.js +3 -3
- package/src/acp/peerProfiles.ts +3 -3
- package/src/agentLoop.js +91 -19
- package/src/agentLoop.ts +102 -22
- package/src/checkpoints.js +23 -5
- package/src/cliMode.js +4 -2
- package/src/commands.js +503 -78
- package/src/contextManager.d.ts +3 -0
- package/src/contextManager.js +78 -5
- package/src/cortex/autoCondenser.js +105 -145
- package/src/cortex/autoCondenser.ts +185 -0
- package/src/cortex/cortexEngine.js +179 -0
- package/src/cortex/cortexEngine.ts +209 -0
- package/src/cortex/provisioner.js +12 -14
- package/src/cortex/provisioner.ts +29 -0
- package/src/cortex/vectorDb.js +307 -386
- package/src/cortex/vectorDb.ts +473 -0
- package/src/decisionPolicy.js +3 -3
- package/src/decisionPolicy.ts +3 -3
- package/src/observer/coldObserver.js +10 -4
- package/src/observer/coldObserver.ts +10 -4
- package/src/observer/evidence.js +8 -3
- package/src/observer/evidence.ts +8 -3
- package/src/reporting.js +30 -7
- package/src/sessionJournal.js +13 -0
- package/src/sessionJournal.ts +13 -0
- package/src/tokenTracker.js +22 -0
- package/src/tokenTracker.ts +28 -0
- package/src/tools/memoryWrite.js +11 -3
- package/src/tools/memoryWrite.ts +12 -3
- package/src/tools/toolSelfRepair.js +11 -0
- package/src/tools/toolSelfRepair.ts +10 -0
- package/src/tui/chatRenderer.js +8 -4
- package/src/tui/completion.js +34 -15
- package/src/tui/composerControls.js +5 -0
- package/src/tui/composerControls.ts +5 -0
- package/src/tui/layout.js +1 -1
- package/src/tui/layout.ts +1 -1
- package/src/tui/messageInteraction.js +1 -1
- package/src/tui/messageInteraction.ts +1 -1
- package/src/tui/observerPicker.js +323 -0
- package/src/tui/observerPicker.ts +386 -0
- package/src/tui/prompt.js +185 -23
- package/src/tui/stage.js +2 -2
- package/src/tui/stageSurface.js +22 -27
- package/src/tui/thinkingBox.js +2 -2
- package/src/tui/thinkingBox.ts +2 -2
- package/src/tui/usageCard.js +178 -0
- package/src/tui/usageCard.ts +240 -0
- package/src/utils/paths.js +30 -1
- package/src/utils/paths.ts +32 -1
- package/src/cortex/autoCondenser.d.ts +0 -2
- package/src/cortex/vectorDb.d.ts +0 -1
package/src/cortex/vectorDb.js
CHANGED
|
@@ -1,28 +1,17 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import crypto from 'crypto';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import os from 'os';
|
|
5
|
-
import { requireCortexModule, provisionCortexDependencies } from './provisioner.js';
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
6
4
|
import { causyneHome } from '../utils/paths.js';
|
|
7
|
-
|
|
5
|
+
import { openCortexDatabase, computeNativeEmbedding, computeSimilarityScore, readExtendedMemoryStats } from './cortexEngine.js';
|
|
8
6
|
// Diagnostics, off by default: console output during a turn overwrites the
|
|
9
7
|
// prompt's live region. See src/cortex/provisioner.js for the full reason.
|
|
10
8
|
function debugLog(message) {
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
if (process.env.CAUSYNE_DEBUG !== '1')
|
|
10
|
+
return;
|
|
11
|
+
process.stderr.write(`[causyne] ${message}\n`);
|
|
13
12
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
// We will load these dynamically after provisioning
|
|
17
|
-
let Database;
|
|
18
|
-
let pipeline;
|
|
19
|
-
let env;
|
|
20
|
-
|
|
21
|
-
// Environment configuration is now done dynamically in init()
|
|
22
|
-
|
|
23
13
|
const CORTEX_DIR = causyneHome();
|
|
24
14
|
const CORTEX_DB_FILE = path.join(CORTEX_DIR, 'cortex.db');
|
|
25
|
-
|
|
26
15
|
/**
|
|
27
16
|
* How long a memory keeps half its weight. Thirty days.
|
|
28
17
|
*
|
|
@@ -31,70 +20,71 @@ const CORTEX_DB_FILE = path.join(CORTEX_DIR, 'cortex.db');
|
|
|
31
20
|
* it just stops an ancient memory outranking a recent one on a tie.
|
|
32
21
|
*/
|
|
33
22
|
const RECENCY_HALF_LIFE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
34
|
-
|
|
35
23
|
/**
|
|
36
24
|
* OBLIVION adaptive memory stability constants:
|
|
37
25
|
* S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
|
|
38
26
|
* R = e^(-t/S) — adaptive retention that rewards retrieved memories with slower decay
|
|
39
27
|
*/
|
|
40
28
|
const REINFORCEMENT_ALPHA = 0.2;
|
|
41
|
-
|
|
42
29
|
const TIER_MULTIPLIERS = {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
30
|
+
condensed: 2.0, // L1: Topic summaries persist longer
|
|
31
|
+
creative: 1.5, // L2: Creative successes are valuable
|
|
32
|
+
mistake: 1.0 // L3: Mistakes decay normally unless reinforced
|
|
46
33
|
};
|
|
47
|
-
|
|
48
34
|
/** Similarity below this is noise, whatever the recency. */
|
|
49
|
-
const MIN_SIMILARITY = 0.
|
|
50
|
-
|
|
35
|
+
const MIN_SIMILARITY = 0.18;
|
|
51
36
|
/** Rows scored per search. Beyond this the newest win, so search stays O(1)-ish. */
|
|
52
37
|
const MAX_CANDIDATES = 500;
|
|
53
|
-
|
|
54
38
|
/** Ceiling on stored memories per workspace before the oldest are retired. */
|
|
55
39
|
const MAX_MEMORIES_PER_WORKSPACE = 2000;
|
|
56
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Common continuation, affirmation, or trivial words that must NEVER trigger
|
|
42
|
+
* historical memory injection. Searching Cortex on "continue" or "next" is what
|
|
43
|
+
* caused catastrophic task hijacking hallucinations (e.g. Suika project bug).
|
|
44
|
+
*/
|
|
45
|
+
const CONTINUATION_WORDS_PATTERN = /^(continue|next|proceed|ok|go|fix|retry|more|run|yes|y|lanjut|teruskan|buka|open|open it)\b/i;
|
|
46
|
+
/**
|
|
47
|
+
* Evaluates whether a prompt carries substantive task content eligible for Cortex retrieval.
|
|
48
|
+
*/
|
|
49
|
+
export function isSearchablePrompt(prompt) {
|
|
50
|
+
if (typeof prompt !== 'string')
|
|
51
|
+
return false;
|
|
52
|
+
const trimmed = prompt.trim();
|
|
53
|
+
if (trimmed.length < 15)
|
|
54
|
+
return false;
|
|
55
|
+
if (CONTINUATION_WORDS_PATTERN.test(trimmed) && trimmed.length < 30)
|
|
56
|
+
return false;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
57
59
|
/** The dedup key: same lesson, same row, however many times it is learned. */
|
|
58
60
|
function fingerprintOf(text) {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
+
const normalised = String(text || '').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
62
|
+
return crypto.createHash('sha256').update(normalised).digest('hex').slice(0, 32);
|
|
61
63
|
}
|
|
62
|
-
|
|
63
64
|
/** Type as a COLUMN, not as a prefix a LIKE has to scan for. */
|
|
64
65
|
function kindOf(text) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
const value = String(text || '');
|
|
67
|
+
if (value.startsWith('CREATIVE SUCCESS:'))
|
|
68
|
+
return 'creative';
|
|
69
|
+
if (value.startsWith('[PAST MISTAKE'))
|
|
70
|
+
return 'mistake';
|
|
71
|
+
return 'condensed';
|
|
69
72
|
}
|
|
70
|
-
|
|
71
73
|
export class VectorDB {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
await provisionCortexDependencies();
|
|
87
|
-
|
|
88
|
-
if (!Database) {
|
|
89
|
-
Database = await requireCortexModule('better-sqlite3');
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Initialize SQLite Database
|
|
93
|
-
this.db = new Database(CORTEX_DB_FILE);
|
|
94
|
-
|
|
95
|
-
// Create the task_memories table if it doesn't exist
|
|
96
|
-
// embedding_vector is stored as a JSON string array of floats
|
|
97
|
-
this.db.exec(`
|
|
74
|
+
extractor = null;
|
|
75
|
+
isInitialized = false;
|
|
76
|
+
isNeural = false;
|
|
77
|
+
db = null;
|
|
78
|
+
async ensureDb() {
|
|
79
|
+
if (this.db)
|
|
80
|
+
return;
|
|
81
|
+
if (!fs.existsSync(CORTEX_DIR)) {
|
|
82
|
+
fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
|
|
83
|
+
}
|
|
84
|
+
this.db = await openCortexDatabase(CORTEX_DB_FILE);
|
|
85
|
+
// Create the task_memories table if it doesn't exist
|
|
86
|
+
// embedding_vector is stored as a JSON string array of floats
|
|
87
|
+
this.db.exec(`
|
|
98
88
|
CREATE TABLE IF NOT EXISTS task_memories (
|
|
99
89
|
id TEXT PRIMARY KEY,
|
|
100
90
|
text TEXT NOT NULL,
|
|
@@ -102,346 +92,277 @@ export class VectorDB {
|
|
|
102
92
|
timestamp INTEGER NOT NULL
|
|
103
93
|
)
|
|
104
94
|
`);
|
|
105
|
-
|
|
106
|
-
this.migrateSchema();
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Bring an existing store up to the current schema, additively.
|
|
111
|
-
*
|
|
112
|
-
* WHAT THE ORIGINAL SCHEMA COULD NOT DO, measured on a real store of 11 rows:
|
|
113
|
-
*
|
|
114
|
-
* - NO WORKSPACE. search() scanned every memory ever recorded, so a lesson
|
|
115
|
-
* learned in one client's repository was injected into another client's
|
|
116
|
-
* task. That is a relevance problem and a CONFIDENTIALITY problem, and it
|
|
117
|
-
* is the same class of bug that made one global chat_history.json resume
|
|
118
|
-
* the wrong project's conversation.
|
|
119
|
-
* - NO DEDUPLICATION. 11 rows held 3 distinct lessons — 73% duplicates. A
|
|
120
|
-
* top-3 search could return the same lesson three times, so the agent paid
|
|
121
|
-
* for three slots and received one.
|
|
122
|
-
* - TIMESTAMP STORED, NEVER USED. A memory from months ago ranked exactly
|
|
123
|
-
* as high as one from yesterday.
|
|
124
|
-
* - TYPE BY STRING PREFIX. Creative patterns were told apart from mistakes
|
|
125
|
-
* with `LIKE 'CREATIVE SUCCESS:%'` — a full table scan against a
|
|
126
|
-
* convention nothing enforced.
|
|
127
|
-
* - NO INDEX beyond the primary key.
|
|
128
|
-
*
|
|
129
|
-
* ALTER TABLE ADD COLUMN is the only migration used: it cannot lose a row,
|
|
130
|
-
* and an interrupted upgrade leaves a store that still reads.
|
|
131
|
-
*/
|
|
132
|
-
migrateSchema() {
|
|
133
|
-
const columns = new Set(this.db.prepare('PRAGMA table_info(task_memories)').all().map(c => c.name));
|
|
134
|
-
|
|
135
|
-
if (!columns.has('workspace')) this.db.exec("ALTER TABLE task_memories ADD COLUMN workspace TEXT DEFAULT ''");
|
|
136
|
-
if (!columns.has('kind')) this.db.exec("ALTER TABLE task_memories ADD COLUMN kind TEXT DEFAULT 'mistake'");
|
|
137
|
-
if (!columns.has('fingerprint')) this.db.exec('ALTER TABLE task_memories ADD COLUMN fingerprint TEXT');
|
|
138
|
-
if (!columns.has('hits')) this.db.exec('ALTER TABLE task_memories ADD COLUMN hits INTEGER DEFAULT 0');
|
|
139
|
-
|
|
140
|
-
// Backfill the two derived columns for rows written before they existed.
|
|
141
|
-
// Existing memories keep workspace '' — global — because we genuinely do
|
|
142
|
-
// not know where they came from, and guessing would attach one project's
|
|
143
|
-
// lesson to another. '' matches every workspace, which is the old
|
|
144
|
-
// behaviour, so nothing a user already relies on disappears.
|
|
145
|
-
const stale = this.db.prepare('SELECT id, text FROM task_memories WHERE fingerprint IS NULL').all();
|
|
146
|
-
if (stale.length > 0) {
|
|
147
|
-
const setRow = this.db.prepare('UPDATE task_memories SET fingerprint = ?, kind = ? WHERE id = ?');
|
|
148
|
-
const run = this.db.transaction((rows) => {
|
|
149
|
-
for (const row of rows) setRow.run(fingerprintOf(row.text), kindOf(row.text), row.id);
|
|
150
|
-
});
|
|
151
|
-
run(stale);
|
|
95
|
+
this.migrateSchema();
|
|
152
96
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
97
|
+
/**
|
|
98
|
+
* Bring an existing store up to the current schema, additively.
|
|
99
|
+
*/
|
|
100
|
+
migrateSchema() {
|
|
101
|
+
if (!this.db)
|
|
102
|
+
return;
|
|
103
|
+
const columns = new Set(this.db.prepare('PRAGMA table_info(task_memories)').all().map((c) => c.name));
|
|
104
|
+
if (!columns.has('workspace'))
|
|
105
|
+
this.db.exec("ALTER TABLE task_memories ADD COLUMN workspace TEXT DEFAULT ''");
|
|
106
|
+
if (!columns.has('kind'))
|
|
107
|
+
this.db.exec("ALTER TABLE task_memories ADD COLUMN kind TEXT DEFAULT 'mistake'");
|
|
108
|
+
if (!columns.has('fingerprint'))
|
|
109
|
+
this.db.exec('ALTER TABLE task_memories ADD COLUMN fingerprint TEXT');
|
|
110
|
+
if (!columns.has('hits'))
|
|
111
|
+
this.db.exec('ALTER TABLE task_memories ADD COLUMN hits INTEGER DEFAULT 0');
|
|
112
|
+
// Backfill derived columns for legacy rows
|
|
113
|
+
const stale = this.db.prepare('SELECT id, text FROM task_memories WHERE fingerprint IS NULL').all();
|
|
114
|
+
if (stale.length > 0) {
|
|
115
|
+
const setRow = this.db.prepare('UPDATE task_memories SET fingerprint = ?, kind = ? WHERE id = ?');
|
|
116
|
+
const run = this.db.transaction((rows) => {
|
|
117
|
+
for (const row of rows)
|
|
118
|
+
setRow.run(fingerprintOf(row.text), kindOf(row.text), row.id);
|
|
119
|
+
});
|
|
120
|
+
run(stale);
|
|
121
|
+
}
|
|
122
|
+
// Collapse legacy duplicates
|
|
123
|
+
const groups = this.db.prepare(`SELECT fingerprint, workspace, COUNT(*) c FROM task_memories
|
|
164
124
|
WHERE fingerprint IS NOT NULL
|
|
165
|
-
GROUP BY fingerprint, workspace HAVING c > 1`
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
125
|
+
GROUP BY fingerprint, workspace HAVING c > 1`).all();
|
|
126
|
+
if (groups.length > 0) {
|
|
127
|
+
const db = this.db;
|
|
128
|
+
const collapse = db.transaction((rows) => {
|
|
129
|
+
for (const group of rows) {
|
|
130
|
+
const copies = db.prepare(`SELECT id, hits FROM task_memories
|
|
131
|
+
WHERE fingerprint = ? AND workspace = ? ORDER BY timestamp DESC`).all(group.fingerprint, group.workspace);
|
|
132
|
+
const keep = copies[0];
|
|
133
|
+
if (!keep)
|
|
134
|
+
continue;
|
|
135
|
+
const totalHits = copies.reduce((sum, row) => sum + (row.hits || 0), 0);
|
|
136
|
+
db.prepare('UPDATE task_memories SET hits = ? WHERE id = ?').run(totalHits, keep.id);
|
|
137
|
+
for (const row of copies.slice(1)) {
|
|
138
|
+
db.prepare('DELETE FROM task_memories WHERE id = ?').run(row.id);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
collapse(groups);
|
|
143
|
+
debugLog(`[CORTEX] collapsed ${groups.length} duplicate group(s)`);
|
|
182
144
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
145
|
+
// Indices for instant lookup
|
|
146
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_ws_time ON task_memories(workspace, timestamp DESC)');
|
|
147
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_kind ON task_memories(kind, timestamp DESC)');
|
|
148
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_fingerprint ON task_memories(fingerprint, workspace)');
|
|
149
|
+
}
|
|
150
|
+
async init() {
|
|
151
|
+
if (this.isInitialized)
|
|
152
|
+
return;
|
|
153
|
+
await this.ensureDb();
|
|
154
|
+
this.extractor = null;
|
|
155
|
+
this.isNeural = false;
|
|
156
|
+
this.isInitialized = true;
|
|
186
157
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
async init() {
|
|
194
|
-
if (this.isInitialized) return;
|
|
195
|
-
|
|
196
|
-
await this.ensureDb();
|
|
197
|
-
|
|
198
|
-
if (!pipeline || !env) {
|
|
199
|
-
const transformers = await requireCortexModule('@xenova/transformers');
|
|
200
|
-
pipeline = transformers.pipeline;
|
|
201
|
-
env = transformers.env;
|
|
202
|
-
|
|
203
|
-
// Optimization: Allow local model caching
|
|
204
|
-
env.localModelPath = path.join(causyneHome(), 'models');
|
|
205
|
-
env.allowRemoteModels = false; // Model provisioning is an explicit setup step.
|
|
158
|
+
async embed(text) {
|
|
159
|
+
if (!this.isInitialized)
|
|
160
|
+
await this.init();
|
|
161
|
+
return computeNativeEmbedding(text);
|
|
206
162
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
163
|
+
cosineSimilarity(vecA, vecB) {
|
|
164
|
+
let dotProduct = 0;
|
|
165
|
+
let normA = 0;
|
|
166
|
+
let normB = 0;
|
|
167
|
+
const len = Math.min(vecA.length, vecB.length);
|
|
168
|
+
for (let i = 0; i < len; i++) {
|
|
169
|
+
const a = vecA[i] ?? 0;
|
|
170
|
+
const b = vecB[i] ?? 0;
|
|
171
|
+
dotProduct += a * b;
|
|
172
|
+
normA += a * a;
|
|
173
|
+
normB += b * b;
|
|
174
|
+
}
|
|
175
|
+
if (normA === 0 || normB === 0)
|
|
176
|
+
return 0;
|
|
177
|
+
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* A mistake and how it was recovered from. Scoped to the project it happened in.
|
|
181
|
+
*/
|
|
182
|
+
async saveMemory(taskGoal, errorEncountered, resolution, workspace = process.cwd()) {
|
|
183
|
+
const searchableText = `Goal: ${taskGoal}\nError: ${errorEncountered}`;
|
|
184
|
+
const fullText = `[PAST MISTAKE RECOVERED]\nGoal: ${taskGoal}\nError: ${errorEncountered}\nResolution: ${resolution}`;
|
|
185
|
+
const result = await this.upsertMemory(fullText, { workspace, kind: 'mistake', searchableText });
|
|
186
|
+
debugLog(`[CORTEX] mistake ${result.created ? 'recorded' : 'reinforced'}`);
|
|
187
|
+
return result;
|
|
215
188
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
// Generate embeddings
|
|
222
|
-
const output = await this.extractor(text, { pooling: 'mean', normalize: true });
|
|
223
|
-
return Array.from(output.data);
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
cosineSimilarity(vecA, vecB) {
|
|
227
|
-
let dotProduct = 0;
|
|
228
|
-
let normA = 0;
|
|
229
|
-
let normB = 0;
|
|
230
|
-
for (let i = 0; i < vecA.length; i++) {
|
|
231
|
-
dotProduct += vecA[i] * vecB[i];
|
|
232
|
-
normA += vecA[i] * vecA[i];
|
|
233
|
-
normB += vecB[i] * vecB[i];
|
|
189
|
+
/** A condensed run of chat history, kept against the project it summarises. */
|
|
190
|
+
async saveCondensedMemory(summaryText, workspace = process.cwd()) {
|
|
191
|
+
const fullText = `[CONDENSED CHAT HISTORY]\n${summaryText}`;
|
|
192
|
+
return this.upsertMemory(fullText, { workspace, kind: 'condensed' });
|
|
234
193
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
*/
|
|
246
|
-
async saveMemory(taskGoal, errorEncountered, resolution, workspace = process.cwd()) {
|
|
247
|
-
const searchableText = `Goal: ${taskGoal}\nError: ${errorEncountered}`;
|
|
248
|
-
const fullText = `[PAST MISTAKE RECOVERED]\nGoal: ${taskGoal}\nError: ${errorEncountered}\nResolution: ${resolution}`;
|
|
249
|
-
const result = await this.upsertMemory(fullText, { workspace, kind: 'mistake', searchableText });
|
|
250
|
-
debugLog(`[CORTEX] mistake ${result.created ? 'recorded' : 'reinforced'}`);
|
|
251
|
-
return result;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/** A condensed run of chat history, kept against the project it summarises. */
|
|
255
|
-
async saveCondensedMemory(summaryText, workspace = process.cwd()) {
|
|
256
|
-
const fullText = `[CONDENSED CHAT HISTORY]\n${summaryText}`;
|
|
257
|
-
return this.upsertMemory(fullText, { workspace, kind: 'condensed' });
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
async search(queryText, topK = 3, options = {}) {
|
|
261
|
-
await this.ensureDb();
|
|
262
|
-
|
|
263
|
-
const workspace = String(options.workspace ?? process.cwd() ?? '');
|
|
264
|
-
const rows = this.db.prepare(
|
|
265
|
-
`SELECT id, text, embedding_vector, timestamp, kind, hits
|
|
194
|
+
async search(queryText, topK = 3, options = {}) {
|
|
195
|
+
// Guard against continuation / short queries to prevent task hijacking hallucinations
|
|
196
|
+
if (!isSearchablePrompt(queryText)) {
|
|
197
|
+
return [];
|
|
198
|
+
}
|
|
199
|
+
await this.ensureDb();
|
|
200
|
+
if (!this.db)
|
|
201
|
+
return [];
|
|
202
|
+
const workspace = String(options.workspace ?? process.cwd() ?? '');
|
|
203
|
+
const rows = this.db.prepare(`SELECT id, text, embedding_vector, timestamp, kind, hits
|
|
266
204
|
FROM task_memories
|
|
267
205
|
WHERE workspace = ? OR workspace = ''
|
|
268
206
|
ORDER BY timestamp DESC
|
|
269
|
-
LIMIT ?`
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
207
|
+
LIMIT ?`).all(workspace, MAX_CANDIDATES);
|
|
208
|
+
if (rows.length === 0)
|
|
209
|
+
return [];
|
|
210
|
+
const queryEmbedding = await this.embed(queryText);
|
|
211
|
+
const now = Date.now();
|
|
212
|
+
const scored = [];
|
|
213
|
+
for (const memory of rows) {
|
|
214
|
+
let similarity;
|
|
215
|
+
try {
|
|
216
|
+
const memVec = JSON.parse(memory.embedding_vector);
|
|
217
|
+
similarity = computeSimilarityScore(queryEmbedding, memVec, queryText, memory.text, Boolean(this.isNeural));
|
|
218
|
+
}
|
|
219
|
+
catch (_e) {
|
|
220
|
+
continue; // a corrupt vector is skipped, never fatal
|
|
221
|
+
}
|
|
222
|
+
if (similarity <= MIN_SIMILARITY)
|
|
223
|
+
continue;
|
|
224
|
+
const ageMs = Math.max(0, now - (memory.timestamp || 0));
|
|
225
|
+
// OBLIVION: S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
|
|
226
|
+
// R = e^(-t/S) — adaptive retention that rewards reinforced memories with slower decay
|
|
227
|
+
const tierMult = TIER_MULTIPLIERS[memory.kind] ?? 1.0;
|
|
228
|
+
const stability = Math.max(1, RECENCY_HALF_LIFE_MS * (1 + (memory.hits || 0) * REINFORCEMENT_ALPHA) * tierMult);
|
|
229
|
+
const retention = Math.exp(-ageMs / stability);
|
|
230
|
+
scored.push({
|
|
231
|
+
id: memory.id,
|
|
232
|
+
text: memory.text,
|
|
233
|
+
kind: memory.kind,
|
|
234
|
+
timestamp: memory.timestamp,
|
|
235
|
+
hits: memory.hits || 0,
|
|
236
|
+
similarity,
|
|
237
|
+
retention,
|
|
238
|
+
score: similarity * retention
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
scored.sort((a, b) => b.score - a.score);
|
|
242
|
+
const matches = scored.slice(0, topK);
|
|
243
|
+
// Reinforce retrieved memories: incrementing hits increases memory stability S
|
|
244
|
+
if (matches.length > 0) {
|
|
245
|
+
try {
|
|
246
|
+
const bump = this.db.prepare('UPDATE task_memories SET hits = hits + 1 WHERE id = ?');
|
|
247
|
+
const run = this.db.transaction((ids) => { for (const id of ids)
|
|
248
|
+
bump.run(id); });
|
|
249
|
+
run(matches.map(m => m.id));
|
|
250
|
+
}
|
|
251
|
+
catch (_e) { /* telemetry must never fail a retrieval */ }
|
|
252
|
+
}
|
|
253
|
+
return matches;
|
|
316
254
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
if (existing) {
|
|
341
|
-
this.db.prepare('UPDATE task_memories SET timestamp = ?, hits = hits + 1 WHERE id = ?')
|
|
342
|
-
.run(Date.now(), existing.id);
|
|
343
|
-
debugLog(`[CORTEX] memory reinforced rather than duplicated: ${fingerprint.slice(0, 8)}`);
|
|
344
|
-
return { id: existing.id, created: false };
|
|
255
|
+
/**
|
|
256
|
+
* Write a memory, or refresh the one that already says this.
|
|
257
|
+
*/
|
|
258
|
+
async upsertMemory(text, { workspace = '', kind = null, searchableText = null } = {}) {
|
|
259
|
+
await this.ensureDb();
|
|
260
|
+
if (!this.db)
|
|
261
|
+
throw new Error('Database not initialized');
|
|
262
|
+
const fingerprint = fingerprintOf(text);
|
|
263
|
+
const scope = String(workspace || '');
|
|
264
|
+
const existing = this.db.prepare('SELECT id FROM task_memories WHERE fingerprint = ? AND workspace = ?').get(fingerprint, scope);
|
|
265
|
+
if (existing) {
|
|
266
|
+
this.db.prepare('UPDATE task_memories SET timestamp = ?, hits = hits + 1 WHERE id = ?')
|
|
267
|
+
.run(Date.now(), existing.id);
|
|
268
|
+
debugLog(`[CORTEX] memory reinforced rather than duplicated: ${fingerprint.slice(0, 8)}`);
|
|
269
|
+
return { id: existing.id, created: false };
|
|
270
|
+
}
|
|
271
|
+
const embedding = await this.embed(searchableText || text);
|
|
272
|
+
const id = `mem_${Date.now()}_${crypto.randomBytes(3).toString('hex')}`;
|
|
273
|
+
this.db.prepare(`INSERT INTO task_memories (id, text, embedding_vector, timestamp, workspace, kind, fingerprint, hits)
|
|
274
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0)`).run(id, text, JSON.stringify(embedding), Date.now(), scope, kind || kindOf(text), fingerprint);
|
|
275
|
+
this.pruneWorkspace(scope);
|
|
276
|
+
return { id, created: true };
|
|
345
277
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
/**
|
|
360
|
-
* Retire the least useful memories once a workspace passes its ceiling.
|
|
361
|
-
*
|
|
362
|
-
* Oldest first, and never-retrieved before ever-retrieved: a memory the agent
|
|
363
|
-
* has actually used is worth more than one that has sat there since August.
|
|
364
|
-
* Called on write rather than on a timer — nothing may run in the background
|
|
365
|
-
* (ZM-01), and a write is exactly when the store can have grown.
|
|
366
|
-
*/
|
|
367
|
-
pruneWorkspace(workspace, max = MAX_MEMORIES_PER_WORKSPACE) {
|
|
368
|
-
try {
|
|
369
|
-
const { c } = this.db.prepare('SELECT COUNT(*) c FROM task_memories WHERE workspace = ?').get(workspace);
|
|
370
|
-
if (c <= max) return 0;
|
|
371
|
-
const result = this.db.prepare(
|
|
372
|
-
`DELETE FROM task_memories WHERE id IN (
|
|
278
|
+
/**
|
|
279
|
+
* Retire the least useful memories once a workspace passes its ceiling.
|
|
280
|
+
*/
|
|
281
|
+
pruneWorkspace(workspace, max = MAX_MEMORIES_PER_WORKSPACE) {
|
|
282
|
+
if (!this.db)
|
|
283
|
+
return 0;
|
|
284
|
+
try {
|
|
285
|
+
const { c } = this.db.prepare('SELECT COUNT(*) c FROM task_memories WHERE workspace = ?').get(workspace);
|
|
286
|
+
if (c <= max)
|
|
287
|
+
return 0;
|
|
288
|
+
const result = this.db.prepare(`DELETE FROM task_memories WHERE id IN (
|
|
373
289
|
SELECT id FROM task_memories WHERE workspace = ?
|
|
374
290
|
ORDER BY hits ASC, timestamp ASC LIMIT ?
|
|
375
|
-
)`
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
291
|
+
)`).run(workspace, c - max);
|
|
292
|
+
return result.changes;
|
|
293
|
+
}
|
|
294
|
+
catch (_e) {
|
|
295
|
+
return 0;
|
|
296
|
+
}
|
|
380
297
|
}
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
: this.db.prepare(
|
|
393
|
-
'SELECT id, text, kind, timestamp, hits, workspace FROM task_memories ORDER BY timestamp DESC LIMIT 200'
|
|
394
|
-
).all();
|
|
395
|
-
return rows;
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
/** Counts, for a one-line answer to "is my digital brain actually on?". */
|
|
399
|
-
async stats() {
|
|
400
|
-
await this.ensureDb();
|
|
401
|
-
const total = this.db.prepare('SELECT COUNT(*) c FROM task_memories').get().c;
|
|
402
|
-
const byKind = this.db.prepare('SELECT kind, COUNT(*) c FROM task_memories GROUP BY kind').all();
|
|
403
|
-
const workspaces = this.db.prepare("SELECT COUNT(DISTINCT workspace) c FROM task_memories WHERE workspace != ''").get().c;
|
|
404
|
-
const newest = this.db.prepare('SELECT MAX(timestamp) t FROM task_memories').get().t || 0;
|
|
405
|
-
const distinct = this.db.prepare('SELECT COUNT(DISTINCT fingerprint) c FROM task_memories').get().c;
|
|
406
|
-
return { total, distinct, byKind, workspaces, newest };
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/** Forget one memory, or every memory in a workspace. */
|
|
410
|
-
async forget({ id = null, workspace = null } = {}) {
|
|
411
|
-
await this.ensureDb();
|
|
412
|
-
if (id) return this.db.prepare('DELETE FROM task_memories WHERE id = ?').run(id).changes;
|
|
413
|
-
if (workspace !== null) {
|
|
414
|
-
return this.db.prepare('DELETE FROM task_memories WHERE workspace = ?').run(String(workspace)).changes;
|
|
298
|
+
/** Everything stored, for `/cortex`. Vectors excluded — they are unreadable. */
|
|
299
|
+
async inventory(options = {}) {
|
|
300
|
+
await this.ensureDb();
|
|
301
|
+
if (!this.db)
|
|
302
|
+
return [];
|
|
303
|
+
const workspace = options.workspace;
|
|
304
|
+
const rows = workspace
|
|
305
|
+
? this.db.prepare(`SELECT id, text, kind, timestamp, hits, workspace FROM task_memories
|
|
306
|
+
WHERE workspace = ? OR workspace = '' ORDER BY timestamp DESC LIMIT 200`).all(String(workspace))
|
|
307
|
+
: this.db.prepare('SELECT id, text, kind, timestamp, hits, workspace FROM task_memories ORDER BY timestamp DESC LIMIT 200').all();
|
|
308
|
+
return rows;
|
|
415
309
|
}
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
310
|
+
/** Counts, for a one-line answer to "is my digital brain actually on?". */
|
|
311
|
+
async stats() {
|
|
312
|
+
await this.ensureDb();
|
|
313
|
+
if (!this.db)
|
|
314
|
+
throw new Error('Database not initialized');
|
|
315
|
+
const total = this.db.prepare('SELECT COUNT(*) c FROM task_memories').get().c;
|
|
316
|
+
const byKind = this.db.prepare('SELECT kind, COUNT(*) c FROM task_memories GROUP BY kind').all();
|
|
317
|
+
const workspaces = this.db.prepare("SELECT COUNT(DISTINCT workspace) c FROM task_memories WHERE workspace != ''").get().c;
|
|
318
|
+
const newest = this.db.prepare('SELECT MAX(timestamp) t FROM task_memories').get().t || 0;
|
|
319
|
+
const distinct = this.db.prepare('SELECT COUNT(DISTINCT fingerprint) c FROM task_memories').get().c;
|
|
320
|
+
const extended = readExtendedMemoryStats();
|
|
321
|
+
return {
|
|
322
|
+
total,
|
|
323
|
+
distinct,
|
|
324
|
+
byKind,
|
|
325
|
+
workspaces,
|
|
326
|
+
newest,
|
|
327
|
+
isNeural: Boolean(this.isNeural),
|
|
328
|
+
engineType: 'native (semantic vector + sqlite)',
|
|
329
|
+
episodicCount: extended.episodicCount,
|
|
330
|
+
factsCount: extended.factsCount
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
/** Forget one memory, or every memory in a workspace. */
|
|
334
|
+
async forget({ id = null, workspace = null } = {}) {
|
|
335
|
+
await this.ensureDb();
|
|
336
|
+
if (!this.db)
|
|
337
|
+
return 0;
|
|
338
|
+
if (id)
|
|
339
|
+
return this.db.prepare('DELETE FROM task_memories WHERE id = ?').run(id).changes;
|
|
340
|
+
if (workspace !== null) {
|
|
341
|
+
return this.db.prepare('DELETE FROM task_memories WHERE workspace = ?').run(String(workspace)).changes;
|
|
342
|
+
}
|
|
343
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* A design approach that worked, so the next one deliberately differs.
|
|
347
|
+
*/
|
|
348
|
+
async saveCreativePattern(pattern) {
|
|
349
|
+
const text = `CREATIVE SUCCESS: Built "${pattern.project}" using ${pattern.designApproach} style. Colors: ${pattern.colorPalette}. Fonts: ${pattern.fonts}.`;
|
|
350
|
+
const result = await this.upsertMemory(text, { workspace: '', kind: 'creative' });
|
|
351
|
+
debugLog(`[CORTEX] creative pattern ${result.created ? 'saved' : 'reinforced'}: ${pattern.designApproach}`);
|
|
352
|
+
return result;
|
|
353
|
+
}
|
|
354
|
+
// Anti-Slop: Retrieve recent creative patterns for the "DO NOT REPEAT" directive
|
|
355
|
+
async getRecentCreativePatterns(limit = 5) {
|
|
356
|
+
await this.ensureDb();
|
|
357
|
+
if (!this.db)
|
|
358
|
+
return [];
|
|
359
|
+
try {
|
|
360
|
+
const results = this.db.prepare('SELECT text FROM task_memories WHERE kind = ? ORDER BY timestamp DESC LIMIT ?').all('creative', limit);
|
|
361
|
+
return results.map((r) => r.text);
|
|
362
|
+
}
|
|
363
|
+
catch (_e) {
|
|
364
|
+
return [];
|
|
365
|
+
}
|
|
443
366
|
}
|
|
444
|
-
}
|
|
445
367
|
}
|
|
446
|
-
|
|
447
368
|
export const cortexDb = new VectorDB();
|