@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
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { causyneHome } from '../utils/paths.js';
|
|
5
|
+
import {
|
|
6
|
+
openCortexDatabase,
|
|
7
|
+
computeNativeEmbedding,
|
|
8
|
+
computeSimilarityScore,
|
|
9
|
+
readExtendedMemoryStats,
|
|
10
|
+
type CortexDatabase
|
|
11
|
+
} from './cortexEngine.js';
|
|
12
|
+
|
|
13
|
+
// Diagnostics, off by default: console output during a turn overwrites the
|
|
14
|
+
// prompt's live region. See src/cortex/provisioner.js for the full reason.
|
|
15
|
+
function debugLog(message: string): void {
|
|
16
|
+
if (process.env.CAUSYNE_DEBUG !== '1') return;
|
|
17
|
+
process.stderr.write(`[causyne] ${message}\n`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const CORTEX_DIR = causyneHome();
|
|
21
|
+
const CORTEX_DB_FILE = path.join(CORTEX_DIR, 'cortex.db');
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How long a memory keeps half its weight. Thirty days.
|
|
25
|
+
*
|
|
26
|
+
* A lesson from last week is usually about the code as it is now; one from
|
|
27
|
+
* March is usually about code that no longer exists. Decay does not delete it —
|
|
28
|
+
* it just stops an ancient memory outranking a recent one on a tie.
|
|
29
|
+
*/
|
|
30
|
+
const RECENCY_HALF_LIFE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* OBLIVION adaptive memory stability constants:
|
|
34
|
+
* S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
|
|
35
|
+
* R = e^(-t/S) — adaptive retention that rewards retrieved memories with slower decay
|
|
36
|
+
*/
|
|
37
|
+
const REINFORCEMENT_ALPHA = 0.2;
|
|
38
|
+
|
|
39
|
+
const TIER_MULTIPLIERS: Record<string, number> = {
|
|
40
|
+
condensed: 2.0, // L1: Topic summaries persist longer
|
|
41
|
+
creative: 1.5, // L2: Creative successes are valuable
|
|
42
|
+
mistake: 1.0 // L3: Mistakes decay normally unless reinforced
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Similarity below this is noise, whatever the recency. */
|
|
46
|
+
const MIN_SIMILARITY = 0.18;
|
|
47
|
+
|
|
48
|
+
/** Rows scored per search. Beyond this the newest win, so search stays O(1)-ish. */
|
|
49
|
+
const MAX_CANDIDATES = 500;
|
|
50
|
+
|
|
51
|
+
/** Ceiling on stored memories per workspace before the oldest are retired. */
|
|
52
|
+
const MAX_MEMORIES_PER_WORKSPACE = 2000;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Common continuation, affirmation, or trivial words that must NEVER trigger
|
|
56
|
+
* historical memory injection. Searching Cortex on "continue" or "next" is what
|
|
57
|
+
* caused catastrophic task hijacking hallucinations (e.g. Suika project bug).
|
|
58
|
+
*/
|
|
59
|
+
const CONTINUATION_WORDS_PATTERN = /^(continue|next|proceed|ok|go|fix|retry|more|run|yes|y|lanjut|teruskan|buka|open|open it)\b/i;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Evaluates whether a prompt carries substantive task content eligible for Cortex retrieval.
|
|
63
|
+
*/
|
|
64
|
+
export function isSearchablePrompt(prompt: unknown): boolean {
|
|
65
|
+
if (typeof prompt !== 'string') return false;
|
|
66
|
+
const trimmed = prompt.trim();
|
|
67
|
+
if (trimmed.length < 15) return false;
|
|
68
|
+
if (CONTINUATION_WORDS_PATTERN.test(trimmed) && trimmed.length < 30) return false;
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The dedup key: same lesson, same row, however many times it is learned. */
|
|
73
|
+
function fingerprintOf(text: string): string {
|
|
74
|
+
const normalised = String(text || '').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
75
|
+
return crypto.createHash('sha256').update(normalised).digest('hex').slice(0, 32);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Type as a COLUMN, not as a prefix a LIKE has to scan for. */
|
|
79
|
+
function kindOf(text: string): string {
|
|
80
|
+
const value = String(text || '');
|
|
81
|
+
if (value.startsWith('CREATIVE SUCCESS:')) return 'creative';
|
|
82
|
+
if (value.startsWith('[PAST MISTAKE')) return 'mistake';
|
|
83
|
+
return 'condensed';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface StoredMemoryRow {
|
|
87
|
+
id: string;
|
|
88
|
+
text: string;
|
|
89
|
+
embedding_vector: string;
|
|
90
|
+
timestamp: number;
|
|
91
|
+
workspace: string;
|
|
92
|
+
kind: string;
|
|
93
|
+
fingerprint: string | null;
|
|
94
|
+
hits: number;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface ScoredMemory {
|
|
98
|
+
id: string;
|
|
99
|
+
text: string;
|
|
100
|
+
kind: string;
|
|
101
|
+
timestamp: number;
|
|
102
|
+
hits: number;
|
|
103
|
+
similarity: number;
|
|
104
|
+
retention: number;
|
|
105
|
+
score: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface UpsertMemoryOptions {
|
|
109
|
+
workspace?: string;
|
|
110
|
+
kind?: string | null;
|
|
111
|
+
searchableText?: string | null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface CreativePattern {
|
|
115
|
+
project: string;
|
|
116
|
+
designApproach: string;
|
|
117
|
+
colorPalette: string;
|
|
118
|
+
fonts: string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export class VectorDB {
|
|
122
|
+
public extractor: null = null;
|
|
123
|
+
public isInitialized: boolean = false;
|
|
124
|
+
public isNeural: boolean = false;
|
|
125
|
+
public db: CortexDatabase | null = null;
|
|
126
|
+
|
|
127
|
+
async ensureDb(): Promise<void> {
|
|
128
|
+
if (this.db) return;
|
|
129
|
+
|
|
130
|
+
if (!fs.existsSync(CORTEX_DIR)) {
|
|
131
|
+
fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
this.db = await openCortexDatabase(CORTEX_DB_FILE);
|
|
135
|
+
|
|
136
|
+
// Create the task_memories table if it doesn't exist
|
|
137
|
+
// embedding_vector is stored as a JSON string array of floats
|
|
138
|
+
this.db.exec(`
|
|
139
|
+
CREATE TABLE IF NOT EXISTS task_memories (
|
|
140
|
+
id TEXT PRIMARY KEY,
|
|
141
|
+
text TEXT NOT NULL,
|
|
142
|
+
embedding_vector TEXT NOT NULL,
|
|
143
|
+
timestamp INTEGER NOT NULL
|
|
144
|
+
)
|
|
145
|
+
`);
|
|
146
|
+
|
|
147
|
+
this.migrateSchema();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Bring an existing store up to the current schema, additively.
|
|
152
|
+
*/
|
|
153
|
+
migrateSchema(): void {
|
|
154
|
+
if (!this.db) return;
|
|
155
|
+
const columns = new Set(this.db.prepare('PRAGMA table_info(task_memories)').all().map((c: any) => c.name));
|
|
156
|
+
|
|
157
|
+
if (!columns.has('workspace')) this.db.exec("ALTER TABLE task_memories ADD COLUMN workspace TEXT DEFAULT ''");
|
|
158
|
+
if (!columns.has('kind')) this.db.exec("ALTER TABLE task_memories ADD COLUMN kind TEXT DEFAULT 'mistake'");
|
|
159
|
+
if (!columns.has('fingerprint')) this.db.exec('ALTER TABLE task_memories ADD COLUMN fingerprint TEXT');
|
|
160
|
+
if (!columns.has('hits')) this.db.exec('ALTER TABLE task_memories ADD COLUMN hits INTEGER DEFAULT 0');
|
|
161
|
+
|
|
162
|
+
// Backfill derived columns for legacy rows
|
|
163
|
+
const stale = this.db.prepare('SELECT id, text FROM task_memories WHERE fingerprint IS NULL').all();
|
|
164
|
+
if (stale.length > 0) {
|
|
165
|
+
const setRow = this.db.prepare('UPDATE task_memories SET fingerprint = ?, kind = ? WHERE id = ?');
|
|
166
|
+
const run = this.db.transaction((rows: any[]) => {
|
|
167
|
+
for (const row of rows) setRow.run(fingerprintOf(row.text), kindOf(row.text), row.id);
|
|
168
|
+
});
|
|
169
|
+
run(stale);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Collapse legacy duplicates
|
|
173
|
+
const groups = this.db.prepare(
|
|
174
|
+
`SELECT fingerprint, workspace, COUNT(*) c FROM task_memories
|
|
175
|
+
WHERE fingerprint IS NOT NULL
|
|
176
|
+
GROUP BY fingerprint, workspace HAVING c > 1`
|
|
177
|
+
).all();
|
|
178
|
+
|
|
179
|
+
if (groups.length > 0) {
|
|
180
|
+
const db = this.db;
|
|
181
|
+
const collapse = db.transaction((rows: any[]) => {
|
|
182
|
+
for (const group of rows) {
|
|
183
|
+
const copies = db.prepare(
|
|
184
|
+
`SELECT id, hits FROM task_memories
|
|
185
|
+
WHERE fingerprint = ? AND workspace = ? ORDER BY timestamp DESC`
|
|
186
|
+
).all(group.fingerprint, group.workspace);
|
|
187
|
+
|
|
188
|
+
const keep = copies[0];
|
|
189
|
+
if (!keep) continue;
|
|
190
|
+
const totalHits = copies.reduce((sum: number, row: any) => sum + (row.hits || 0), 0);
|
|
191
|
+
db.prepare('UPDATE task_memories SET hits = ? WHERE id = ?').run(totalHits, keep.id);
|
|
192
|
+
for (const row of copies.slice(1)) {
|
|
193
|
+
db.prepare('DELETE FROM task_memories WHERE id = ?').run(row.id);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
collapse(groups);
|
|
198
|
+
debugLog(`[CORTEX] collapsed ${groups.length} duplicate group(s)`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Indices for instant lookup
|
|
202
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_ws_time ON task_memories(workspace, timestamp DESC)');
|
|
203
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_kind ON task_memories(kind, timestamp DESC)');
|
|
204
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_fingerprint ON task_memories(fingerprint, workspace)');
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async init(): Promise<void> {
|
|
208
|
+
if (this.isInitialized) return;
|
|
209
|
+
await this.ensureDb();
|
|
210
|
+
this.extractor = null;
|
|
211
|
+
this.isNeural = false;
|
|
212
|
+
this.isInitialized = true;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async embed(text: string): Promise<number[]> {
|
|
216
|
+
if (!this.isInitialized) await this.init();
|
|
217
|
+
return computeNativeEmbedding(text);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
cosineSimilarity(vecA: number[], vecB: number[]): number {
|
|
221
|
+
let dotProduct = 0;
|
|
222
|
+
let normA = 0;
|
|
223
|
+
let normB = 0;
|
|
224
|
+
const len = Math.min(vecA.length, vecB.length);
|
|
225
|
+
for (let i = 0; i < len; i++) {
|
|
226
|
+
const a = vecA[i] ?? 0;
|
|
227
|
+
const b = vecB[i] ?? 0;
|
|
228
|
+
dotProduct += a * b;
|
|
229
|
+
normA += a * a;
|
|
230
|
+
normB += b * b;
|
|
231
|
+
}
|
|
232
|
+
if (normA === 0 || normB === 0) return 0;
|
|
233
|
+
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A mistake and how it was recovered from. Scoped to the project it happened in.
|
|
238
|
+
*/
|
|
239
|
+
async saveMemory(
|
|
240
|
+
taskGoal: string,
|
|
241
|
+
errorEncountered: string,
|
|
242
|
+
resolution: string,
|
|
243
|
+
workspace: string = process.cwd()
|
|
244
|
+
): Promise<{ id: string; created: boolean }> {
|
|
245
|
+
const searchableText = `Goal: ${taskGoal}\nError: ${errorEncountered}`;
|
|
246
|
+
const fullText = `[PAST MISTAKE RECOVERED]\nGoal: ${taskGoal}\nError: ${errorEncountered}\nResolution: ${resolution}`;
|
|
247
|
+
const result = await this.upsertMemory(fullText, { workspace, kind: 'mistake', searchableText });
|
|
248
|
+
debugLog(`[CORTEX] mistake ${result.created ? 'recorded' : 'reinforced'}`);
|
|
249
|
+
return result;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** A condensed run of chat history, kept against the project it summarises. */
|
|
253
|
+
async saveCondensedMemory(
|
|
254
|
+
summaryText: string,
|
|
255
|
+
workspace: string = process.cwd()
|
|
256
|
+
): Promise<{ id: string; created: boolean }> {
|
|
257
|
+
const fullText = `[CONDENSED CHAT HISTORY]\n${summaryText}`;
|
|
258
|
+
return this.upsertMemory(fullText, { workspace, kind: 'condensed' });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async search(
|
|
262
|
+
queryText: string,
|
|
263
|
+
topK: number = 3,
|
|
264
|
+
options: { workspace?: string } = {}
|
|
265
|
+
): Promise<ScoredMemory[]> {
|
|
266
|
+
// Guard against continuation / short queries to prevent task hijacking hallucinations
|
|
267
|
+
if (!isSearchablePrompt(queryText)) {
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
await this.ensureDb();
|
|
272
|
+
if (!this.db) return [];
|
|
273
|
+
|
|
274
|
+
const workspace = String(options.workspace ?? process.cwd() ?? '');
|
|
275
|
+
const rows: StoredMemoryRow[] = this.db.prepare(
|
|
276
|
+
`SELECT id, text, embedding_vector, timestamp, kind, hits
|
|
277
|
+
FROM task_memories
|
|
278
|
+
WHERE workspace = ? OR workspace = ''
|
|
279
|
+
ORDER BY timestamp DESC
|
|
280
|
+
LIMIT ?`
|
|
281
|
+
).all(workspace, MAX_CANDIDATES);
|
|
282
|
+
|
|
283
|
+
if (rows.length === 0) return [];
|
|
284
|
+
|
|
285
|
+
const queryEmbedding = await this.embed(queryText);
|
|
286
|
+
const now = Date.now();
|
|
287
|
+
|
|
288
|
+
const scored: ScoredMemory[] = [];
|
|
289
|
+
for (const memory of rows) {
|
|
290
|
+
let similarity: number;
|
|
291
|
+
try {
|
|
292
|
+
const memVec = JSON.parse(memory.embedding_vector);
|
|
293
|
+
similarity = computeSimilarityScore(queryEmbedding, memVec, queryText, memory.text, Boolean(this.isNeural));
|
|
294
|
+
} catch (_e) {
|
|
295
|
+
continue; // a corrupt vector is skipped, never fatal
|
|
296
|
+
}
|
|
297
|
+
if (similarity <= MIN_SIMILARITY) continue;
|
|
298
|
+
|
|
299
|
+
const ageMs = Math.max(0, now - (memory.timestamp || 0));
|
|
300
|
+
// OBLIVION: S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
|
|
301
|
+
// R = e^(-t/S) — adaptive retention that rewards reinforced memories with slower decay
|
|
302
|
+
const tierMult = TIER_MULTIPLIERS[memory.kind] ?? 1.0;
|
|
303
|
+
const stability = Math.max(1, RECENCY_HALF_LIFE_MS * (1 + (memory.hits || 0) * REINFORCEMENT_ALPHA) * tierMult);
|
|
304
|
+
const retention = Math.exp(-ageMs / stability);
|
|
305
|
+
scored.push({
|
|
306
|
+
id: memory.id,
|
|
307
|
+
text: memory.text,
|
|
308
|
+
kind: memory.kind,
|
|
309
|
+
timestamp: memory.timestamp,
|
|
310
|
+
hits: memory.hits || 0,
|
|
311
|
+
similarity,
|
|
312
|
+
retention,
|
|
313
|
+
score: similarity * retention
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
scored.sort((a, b) => b.score - a.score);
|
|
318
|
+
const matches = scored.slice(0, topK);
|
|
319
|
+
|
|
320
|
+
// Reinforce retrieved memories: incrementing hits increases memory stability S
|
|
321
|
+
if (matches.length > 0) {
|
|
322
|
+
try {
|
|
323
|
+
const bump = this.db.prepare('UPDATE task_memories SET hits = hits + 1 WHERE id = ?');
|
|
324
|
+
const run = this.db.transaction((ids: string[]) => { for (const id of ids) bump.run(id); });
|
|
325
|
+
run(matches.map(m => m.id));
|
|
326
|
+
} catch (_e) { /* telemetry must never fail a retrieval */ }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return matches;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Write a memory, or refresh the one that already says this.
|
|
334
|
+
*/
|
|
335
|
+
async upsertMemory(
|
|
336
|
+
text: string,
|
|
337
|
+
{ workspace = '', kind = null, searchableText = null }: UpsertMemoryOptions = {}
|
|
338
|
+
): Promise<{ id: string; created: boolean }> {
|
|
339
|
+
await this.ensureDb();
|
|
340
|
+
if (!this.db) throw new Error('Database not initialized');
|
|
341
|
+
|
|
342
|
+
const fingerprint = fingerprintOf(text);
|
|
343
|
+
const scope = String(workspace || '');
|
|
344
|
+
|
|
345
|
+
const existing = this.db.prepare(
|
|
346
|
+
'SELECT id FROM task_memories WHERE fingerprint = ? AND workspace = ?'
|
|
347
|
+
).get(fingerprint, scope);
|
|
348
|
+
|
|
349
|
+
if (existing) {
|
|
350
|
+
this.db.prepare('UPDATE task_memories SET timestamp = ?, hits = hits + 1 WHERE id = ?')
|
|
351
|
+
.run(Date.now(), existing.id);
|
|
352
|
+
debugLog(`[CORTEX] memory reinforced rather than duplicated: ${fingerprint.slice(0, 8)}`);
|
|
353
|
+
return { id: existing.id, created: false };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const embedding = await this.embed(searchableText || text);
|
|
357
|
+
const id = `mem_${Date.now()}_${crypto.randomBytes(3).toString('hex')}`;
|
|
358
|
+
|
|
359
|
+
this.db.prepare(
|
|
360
|
+
`INSERT INTO task_memories (id, text, embedding_vector, timestamp, workspace, kind, fingerprint, hits)
|
|
361
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0)`
|
|
362
|
+
).run(id, text, JSON.stringify(embedding), Date.now(), scope, kind || kindOf(text), fingerprint);
|
|
363
|
+
|
|
364
|
+
this.pruneWorkspace(scope);
|
|
365
|
+
return { id, created: true };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Retire the least useful memories once a workspace passes its ceiling.
|
|
370
|
+
*/
|
|
371
|
+
pruneWorkspace(workspace: string, max: number = MAX_MEMORIES_PER_WORKSPACE): number {
|
|
372
|
+
if (!this.db) return 0;
|
|
373
|
+
try {
|
|
374
|
+
const { c } = this.db.prepare('SELECT COUNT(*) c FROM task_memories WHERE workspace = ?').get(workspace);
|
|
375
|
+
if (c <= max) return 0;
|
|
376
|
+
const result = this.db.prepare(
|
|
377
|
+
`DELETE FROM task_memories WHERE id IN (
|
|
378
|
+
SELECT id FROM task_memories WHERE workspace = ?
|
|
379
|
+
ORDER BY hits ASC, timestamp ASC LIMIT ?
|
|
380
|
+
)`
|
|
381
|
+
).run(workspace, c - max);
|
|
382
|
+
return result.changes;
|
|
383
|
+
} catch (_e) {
|
|
384
|
+
return 0;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Everything stored, for `/cortex`. Vectors excluded — they are unreadable. */
|
|
389
|
+
async inventory(options: { workspace?: string } = {}): Promise<any[]> {
|
|
390
|
+
await this.ensureDb();
|
|
391
|
+
if (!this.db) return [];
|
|
392
|
+
const workspace = options.workspace;
|
|
393
|
+
const rows = workspace
|
|
394
|
+
? this.db.prepare(
|
|
395
|
+
`SELECT id, text, kind, timestamp, hits, workspace FROM task_memories
|
|
396
|
+
WHERE workspace = ? OR workspace = '' ORDER BY timestamp DESC LIMIT 200`
|
|
397
|
+
).all(String(workspace))
|
|
398
|
+
: this.db.prepare(
|
|
399
|
+
'SELECT id, text, kind, timestamp, hits, workspace FROM task_memories ORDER BY timestamp DESC LIMIT 200'
|
|
400
|
+
).all();
|
|
401
|
+
return rows;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Counts, for a one-line answer to "is my digital brain actually on?". */
|
|
405
|
+
async stats(): Promise<{
|
|
406
|
+
total: number;
|
|
407
|
+
distinct: number;
|
|
408
|
+
byKind: Array<{ kind: string; c: number }>;
|
|
409
|
+
workspaces: number;
|
|
410
|
+
newest: number;
|
|
411
|
+
isNeural: boolean;
|
|
412
|
+
engineType: string;
|
|
413
|
+
episodicCount: number;
|
|
414
|
+
factsCount: number;
|
|
415
|
+
}> {
|
|
416
|
+
await this.ensureDb();
|
|
417
|
+
if (!this.db) throw new Error('Database not initialized');
|
|
418
|
+
const total = this.db.prepare('SELECT COUNT(*) c FROM task_memories').get().c;
|
|
419
|
+
const byKind = this.db.prepare('SELECT kind, COUNT(*) c FROM task_memories GROUP BY kind').all();
|
|
420
|
+
const workspaces = this.db.prepare("SELECT COUNT(DISTINCT workspace) c FROM task_memories WHERE workspace != ''").get().c;
|
|
421
|
+
const newest = this.db.prepare('SELECT MAX(timestamp) t FROM task_memories').get().t || 0;
|
|
422
|
+
const distinct = this.db.prepare('SELECT COUNT(DISTINCT fingerprint) c FROM task_memories').get().c;
|
|
423
|
+
const extended = readExtendedMemoryStats();
|
|
424
|
+
return {
|
|
425
|
+
total,
|
|
426
|
+
distinct,
|
|
427
|
+
byKind,
|
|
428
|
+
workspaces,
|
|
429
|
+
newest,
|
|
430
|
+
isNeural: Boolean(this.isNeural),
|
|
431
|
+
engineType: 'native (semantic vector + sqlite)',
|
|
432
|
+
episodicCount: extended.episodicCount,
|
|
433
|
+
factsCount: extended.factsCount
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Forget one memory, or every memory in a workspace. */
|
|
438
|
+
async forget({ id = null, workspace = null }: { id?: string | null; workspace?: string | null } = {}): Promise<number> {
|
|
439
|
+
await this.ensureDb();
|
|
440
|
+
if (!this.db) return 0;
|
|
441
|
+
if (id) return this.db.prepare('DELETE FROM task_memories WHERE id = ?').run(id).changes;
|
|
442
|
+
if (workspace !== null) {
|
|
443
|
+
return this.db.prepare('DELETE FROM task_memories WHERE workspace = ?').run(String(workspace)).changes;
|
|
444
|
+
}
|
|
445
|
+
return 0;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* A design approach that worked, so the next one deliberately differs.
|
|
450
|
+
*/
|
|
451
|
+
async saveCreativePattern(pattern: CreativePattern): Promise<{ id: string; created: boolean }> {
|
|
452
|
+
const text = `CREATIVE SUCCESS: Built "${pattern.project}" using ${pattern.designApproach} style. Colors: ${pattern.colorPalette}. Fonts: ${pattern.fonts}.`;
|
|
453
|
+
const result = await this.upsertMemory(text, { workspace: '', kind: 'creative' });
|
|
454
|
+
debugLog(`[CORTEX] creative pattern ${result.created ? 'saved' : 'reinforced'}: ${pattern.designApproach}`);
|
|
455
|
+
return result;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Anti-Slop: Retrieve recent creative patterns for the "DO NOT REPEAT" directive
|
|
459
|
+
async getRecentCreativePatterns(limit: number = 5): Promise<string[]> {
|
|
460
|
+
await this.ensureDb();
|
|
461
|
+
if (!this.db) return [];
|
|
462
|
+
try {
|
|
463
|
+
const results = this.db.prepare(
|
|
464
|
+
'SELECT text FROM task_memories WHERE kind = ? ORDER BY timestamp DESC LIMIT ?'
|
|
465
|
+
).all('creative', limit);
|
|
466
|
+
return results.map((r: any) => r.text);
|
|
467
|
+
} catch (_e) {
|
|
468
|
+
return [];
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export const cortexDb = new VectorDB();
|
package/src/decisionPolicy.js
CHANGED
|
@@ -18,7 +18,7 @@ const MUTATING_TOOLS = new Set([
|
|
|
18
18
|
'fs_write', 'fs_edit', 'MultiEdit', 'fs_delete', 'fs_move', 'sysRun', 'sysRunBg',
|
|
19
19
|
'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'plugins_factory', 'create_skill',
|
|
20
20
|
'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content',
|
|
21
|
-
'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute', 'run_command'
|
|
21
|
+
'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute', 'run_command', 'run'
|
|
22
22
|
]);
|
|
23
23
|
function splitCommandSegments(command) {
|
|
24
24
|
const segments = [];
|
|
@@ -138,8 +138,8 @@ export function isMutatingToolCall(toolName, args = {}) {
|
|
|
138
138
|
if (toolName === 'native_engine')
|
|
139
139
|
return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
|
|
140
140
|
if (MUTATING_TOOLS.has(toolName)) {
|
|
141
|
-
if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh', 'run_command'].includes(toolName)) {
|
|
142
|
-
const command = String(args.command ?? args.cmd ?? '');
|
|
141
|
+
if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh', 'run_command', 'run'].includes(toolName)) {
|
|
142
|
+
const command = String(args.CommandLine ?? args.commandLine ?? args.command ?? args.cmd ?? args.script ?? args.code ?? '');
|
|
143
143
|
return !isReadOnlyShellCommand(command);
|
|
144
144
|
}
|
|
145
145
|
if (toolName === 'gitOp') {
|
package/src/decisionPolicy.ts
CHANGED
|
@@ -52,7 +52,7 @@ const MUTATING_TOOLS = new Set([
|
|
|
52
52
|
'fs_write', 'fs_edit', 'MultiEdit', 'fs_delete', 'fs_move', 'sysRun', 'sysRunBg',
|
|
53
53
|
'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'plugins_factory', 'create_skill',
|
|
54
54
|
'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content',
|
|
55
|
-
'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute', 'run_command'
|
|
55
|
+
'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute', 'run_command', 'run'
|
|
56
56
|
]);
|
|
57
57
|
|
|
58
58
|
function splitCommandSegments(command: string): string[] {
|
|
@@ -175,8 +175,8 @@ export function isMutatingToolCall(toolName: string, args: Record<string, unknow
|
|
|
175
175
|
}
|
|
176
176
|
if (toolName === 'native_engine') return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
|
|
177
177
|
if (MUTATING_TOOLS.has(toolName)) {
|
|
178
|
-
if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh', 'run_command'].includes(toolName)) {
|
|
179
|
-
const command = String(args.command ?? args.cmd ?? '');
|
|
178
|
+
if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh', 'run_command', 'run'].includes(toolName)) {
|
|
179
|
+
const command = String(args.CommandLine ?? args.commandLine ?? args.command ?? args.cmd ?? args.script ?? args.code ?? '');
|
|
180
180
|
return !isReadOnlyShellCommand(command);
|
|
181
181
|
}
|
|
182
182
|
if (toolName === 'gitOp') {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { auditLog } from '../auditLog.js';
|
|
4
|
+
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
4
5
|
import { causyneHome } from '../utils/paths.js';
|
|
5
6
|
import { boundedArgs, outcomeFromResult, scanMutation } from './evidence.js';
|
|
6
7
|
import { isLoopbackEndpoint, probeAdvisory, queryAdvisory } from './advisory.js';
|
|
@@ -130,7 +131,11 @@ function normalizeOutcome(entry) {
|
|
|
130
131
|
const error = nestedError(result);
|
|
131
132
|
const command = entry.command
|
|
132
133
|
|| (typeof args.command === 'string' ? args.command : '')
|
|
133
|
-
|| (typeof args.
|
|
134
|
+
|| (typeof args.CommandLine === 'string' ? args.CommandLine : '')
|
|
135
|
+
|| (typeof args.commandLine === 'string' ? args.commandLine : '')
|
|
136
|
+
|| (typeof args.cmd === 'string' ? args.cmd : '')
|
|
137
|
+
|| (typeof args.script === 'string' ? args.script : '')
|
|
138
|
+
|| (['run_command', 'run', 'execute', 'exec', 'bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes(String(entry.tool || '').toLowerCase()) && typeof args.detail === 'string' ? args.detail : '');
|
|
134
139
|
return {
|
|
135
140
|
tool: entry.tool,
|
|
136
141
|
args: boundedArgs(args),
|
|
@@ -395,6 +400,7 @@ export class ColdObserver {
|
|
|
395
400
|
&& (TEST_COMMAND.test(outcome.command) || TEST_COMMAND.test(outcome.tool)));
|
|
396
401
|
const hasBuildRun = checks.some((outcome) => outcome.success
|
|
397
402
|
&& (BUILD_OR_CHECK_COMMAND.test(outcome.command) || outcome.tool === 'code_verify_syntax'));
|
|
403
|
+
const isLaunch = isLaunchOnlyPrompt(turnState.userPrompt || '');
|
|
398
404
|
const modifiedCode = lastCodeChange >= 0;
|
|
399
405
|
const declarativeOnly = modifiedCode && outcomes.filter(isCodeMutation).every(outcome => /\.(?:html|css)$/i.test(outcome.path));
|
|
400
406
|
const hasRenderedCheck = checks.some(outcome => outcome.success && outcome.rendered === true);
|
|
@@ -411,19 +417,19 @@ export class ColdObserver {
|
|
|
411
417
|
discrepancy = `completion claim conflicts with tool evidence: ${failureSummary(outcomes)}`;
|
|
412
418
|
coldDirective = `[OBSERVER] Your completion claim conflicts with the latest tool evidence: ${failureSummary(outcomes)}. Resolve the failure and rerun the failing check before claiming success.`;
|
|
413
419
|
}
|
|
414
|
-
else if (!caveat && TESTS_CLAIM.test(claim) && !hasTestRun) {
|
|
420
|
+
else if (!caveat && !isLaunch && modifiedCode && TESTS_CLAIM.test(claim) && !hasTestRun) {
|
|
415
421
|
overconfident = true;
|
|
416
422
|
confidence = 0.86;
|
|
417
423
|
discrepancy = 'claimed passing tests without a successful test command in this task';
|
|
418
424
|
coldDirective = '[OBSERVER] You claimed that tests passed, but no successful test command appears in this task. Run the test command and report its actual result, or state plainly that you did not run it.';
|
|
419
425
|
}
|
|
420
|
-
else if (!caveat && BUILD_CLAIM.test(claim) && !hasBuildRun) {
|
|
426
|
+
else if (!caveat && !isLaunch && modifiedCode && BUILD_CLAIM.test(claim) && !hasBuildRun) {
|
|
421
427
|
overconfident = true;
|
|
422
428
|
confidence = 0.82;
|
|
423
429
|
discrepancy = 'claimed a passing build or check without a successful verification command';
|
|
424
430
|
coldDirective = '[OBSERVER] You claimed that a build or check passed, but no successful verification command appears in this task. Run the relevant command and report its actual result, or state that it is unverified.';
|
|
425
431
|
}
|
|
426
|
-
else if (!caveat && modifiedCode && !hasBuildRun && !hasTestRun && !(declarativeOnly && (hasRenderedCheck || hasDeclarativeInspection))) {
|
|
432
|
+
else if (!caveat && !isLaunch && modifiedCode && !hasBuildRun && !hasTestRun && !(declarativeOnly && (hasRenderedCheck || hasDeclarativeInspection))) {
|
|
427
433
|
overconfident = true;
|
|
428
434
|
confidence = 0.72;
|
|
429
435
|
discrepancy = 'code was modified without a successful test or syntax check';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { auditLog } from '../auditLog.js';
|
|
4
|
+
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
4
5
|
import { causyneHome } from '../utils/paths.js';
|
|
5
6
|
import {
|
|
6
7
|
boundedArgs,
|
|
@@ -184,7 +185,11 @@ function normalizeOutcome(entry: TurnToolEvidence): ToolOutcome {
|
|
|
184
185
|
const error = nestedError(result);
|
|
185
186
|
const command = entry.command
|
|
186
187
|
|| (typeof args.command === 'string' ? args.command : '')
|
|
187
|
-
|| (typeof args.
|
|
188
|
+
|| (typeof args.CommandLine === 'string' ? args.CommandLine : '')
|
|
189
|
+
|| (typeof args.commandLine === 'string' ? args.commandLine : '')
|
|
190
|
+
|| (typeof args.cmd === 'string' ? args.cmd : '')
|
|
191
|
+
|| (typeof args.script === 'string' ? args.script : '')
|
|
192
|
+
|| (['run_command', 'run', 'execute', 'exec', 'bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes(String(entry.tool || '').toLowerCase()) && typeof args.detail === 'string' ? args.detail : '');
|
|
188
193
|
return {
|
|
189
194
|
tool: entry.tool,
|
|
190
195
|
args: boundedArgs(args),
|
|
@@ -472,6 +477,7 @@ export class ColdObserver {
|
|
|
472
477
|
&& (TEST_COMMAND.test(outcome.command) || TEST_COMMAND.test(outcome.tool)));
|
|
473
478
|
const hasBuildRun = checks.some((outcome) => outcome.success
|
|
474
479
|
&& (BUILD_OR_CHECK_COMMAND.test(outcome.command) || outcome.tool === 'code_verify_syntax'));
|
|
480
|
+
const isLaunch = isLaunchOnlyPrompt(turnState.userPrompt || '');
|
|
475
481
|
const modifiedCode = lastCodeChange >= 0;
|
|
476
482
|
const declarativeOnly = modifiedCode && outcomes.filter(isCodeMutation).every(outcome => /\.(?:html|css)$/i.test(outcome.path));
|
|
477
483
|
const hasRenderedCheck = checks.some(outcome => outcome.success && outcome.rendered === true);
|
|
@@ -489,17 +495,17 @@ export class ColdObserver {
|
|
|
489
495
|
confidence = 0.92;
|
|
490
496
|
discrepancy = `completion claim conflicts with tool evidence: ${failureSummary(outcomes)}`;
|
|
491
497
|
coldDirective = `[OBSERVER] Your completion claim conflicts with the latest tool evidence: ${failureSummary(outcomes)}. Resolve the failure and rerun the failing check before claiming success.`;
|
|
492
|
-
} else if (!caveat && TESTS_CLAIM.test(claim) && !hasTestRun) {
|
|
498
|
+
} else if (!caveat && !isLaunch && modifiedCode && TESTS_CLAIM.test(claim) && !hasTestRun) {
|
|
493
499
|
overconfident = true;
|
|
494
500
|
confidence = 0.86;
|
|
495
501
|
discrepancy = 'claimed passing tests without a successful test command in this task';
|
|
496
502
|
coldDirective = '[OBSERVER] You claimed that tests passed, but no successful test command appears in this task. Run the test command and report its actual result, or state plainly that you did not run it.';
|
|
497
|
-
} else if (!caveat && BUILD_CLAIM.test(claim) && !hasBuildRun) {
|
|
503
|
+
} else if (!caveat && !isLaunch && modifiedCode && BUILD_CLAIM.test(claim) && !hasBuildRun) {
|
|
498
504
|
overconfident = true;
|
|
499
505
|
confidence = 0.82;
|
|
500
506
|
discrepancy = 'claimed a passing build or check without a successful verification command';
|
|
501
507
|
coldDirective = '[OBSERVER] You claimed that a build or check passed, but no successful verification command appears in this task. Run the relevant command and report its actual result, or state that it is unverified.';
|
|
502
|
-
} else if (!caveat && modifiedCode && !hasBuildRun && !hasTestRun && !(declarativeOnly && (hasRenderedCheck || hasDeclarativeInspection))) {
|
|
508
|
+
} else if (!caveat && !isLaunch && modifiedCode && !hasBuildRun && !hasTestRun && !(declarativeOnly && (hasRenderedCheck || hasDeclarativeInspection))) {
|
|
503
509
|
overconfident = true;
|
|
504
510
|
confidence = 0.72;
|
|
505
511
|
discrepancy = 'code was modified without a successful test or syntax check';
|
package/src/observer/evidence.js
CHANGED
|
@@ -425,9 +425,14 @@ export function outcomeFromResult(tool, args, result, at) {
|
|
|
425
425
|
const success = record.success !== false && typeof record.error !== 'string';
|
|
426
426
|
const rawError = typeof record.error === 'string' ? record.error : '';
|
|
427
427
|
const exitCode = typeof record.exitCode === 'number' && Number.isFinite(record.exitCode) ? record.exitCode : null;
|
|
428
|
-
const
|
|
429
|
-
? args.
|
|
430
|
-
|
|
428
|
+
const rawCommand = typeof args.command === 'string' ? args.command
|
|
429
|
+
: typeof args.CommandLine === 'string' ? args.CommandLine
|
|
430
|
+
: typeof args.commandLine === 'string' ? args.commandLine
|
|
431
|
+
: typeof args.cmd === 'string' ? args.cmd
|
|
432
|
+
: typeof args.script === 'string' ? args.script
|
|
433
|
+
: (['run_command', 'run', 'execute', 'exec', 'bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes((tool || '').toLowerCase()) && typeof args.detail === 'string') ? args.detail
|
|
434
|
+
: '';
|
|
435
|
+
const command = rawCommand.trim();
|
|
431
436
|
const browserData = Array.isArray(record.data) ? record.data : [];
|
|
432
437
|
const imageCaptured = success && record._is_image_marker === true;
|
|
433
438
|
const observedImage = imageCaptured && record.visionDelivered !== false;
|
package/src/observer/evidence.ts
CHANGED
|
@@ -489,9 +489,14 @@ export function outcomeFromResult(tool: string, args: Record<string, unknown>, r
|
|
|
489
489
|
const success = record.success !== false && typeof record.error !== 'string';
|
|
490
490
|
const rawError = typeof record.error === 'string' ? record.error : '';
|
|
491
491
|
const exitCode = typeof record.exitCode === 'number' && Number.isFinite(record.exitCode) ? record.exitCode : null;
|
|
492
|
-
const
|
|
493
|
-
? args.
|
|
494
|
-
: typeof args.
|
|
492
|
+
const rawCommand = typeof args.command === 'string' ? args.command
|
|
493
|
+
: typeof args.CommandLine === 'string' ? args.CommandLine
|
|
494
|
+
: typeof args.commandLine === 'string' ? args.commandLine
|
|
495
|
+
: typeof args.cmd === 'string' ? args.cmd
|
|
496
|
+
: typeof args.script === 'string' ? args.script
|
|
497
|
+
: (['run_command', 'run', 'execute', 'exec', 'bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes((tool || '').toLowerCase()) && typeof args.detail === 'string') ? args.detail
|
|
498
|
+
: '';
|
|
499
|
+
const command = rawCommand.trim();
|
|
495
500
|
const browserData = Array.isArray(record.data) ? record.data : [];
|
|
496
501
|
const imageCaptured = success && record._is_image_marker === true;
|
|
497
502
|
const observedImage = imageCaptured && record.visionDelivered !== false;
|