@causyne/agent 1.20.60 → 1.20.63
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/README.md +2 -2
- package/package.json +1 -1
- package/src/acp/agentCatalog.js +1 -1
- package/src/acp/agentCatalog.ts +1 -1
- package/src/acp/client.js +48 -0
- package/src/acp/client.ts +44 -0
- package/src/acp/peerProfiles.js +3 -3
- package/src/acp/peerProfiles.ts +3 -3
- package/src/agentLoop.js +239 -33
- package/src/agentLoop.ts +248 -36
- package/src/checkpoints.js +23 -5
- package/src/cliMode.js +13 -2
- package/src/commands.js +534 -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 +18 -1
- package/src/decisionPolicy.ts +18 -1
- package/src/implementationPlan.js +26 -0
- package/src/implementationPlan.ts +25 -0
- package/src/observer/coldObserver.js +6 -1
- package/src/observer/coldObserver.ts +6 -1
- package/src/observer.js +24 -2
- package/src/observer.ts +24 -2
- package/src/providers/acp.js +2 -8
- package/src/providers/acp.ts +2 -8
- package/src/providers/antigravity.js +7 -10
- package/src/providers/antigravity.ts +7 -10
- package/src/reporting.js +30 -7
- package/src/sessionJournal.js +13 -0
- package/src/sessionJournal.ts +13 -0
- package/src/smartToolsUse.js +1 -1
- package/src/smartToolsUse.ts +1 -1
- package/src/tokenTracker.js +22 -0
- package/src/tokenTracker.ts +28 -0
- package/src/toolPacks.js +1 -1
- package/src/toolPacks.ts +1 -1
- package/src/tools/toolSelfRepair.js +51 -8
- package/src/tools/toolSelfRepair.ts +42 -9
- package/src/tui/CausyneRotor.js +234 -0
- package/src/tui/CausyneRotor.ts +280 -0
- package/src/tui/activityLayout.js +1 -1
- package/src/tui/activityLayout.ts +1 -1
- package/src/tui/chatRenderer.js +62 -9
- package/src/tui/chatboxClipboard.js +96 -10
- package/src/tui/chatboxClipboard.ts +121 -11
- package/src/tui/clipboardImage.js +308 -0
- package/src/tui/clipboardImage.ts +320 -0
- package/src/tui/codeStreamRenderer.js +89 -1
- package/src/tui/codeStreamRenderer.ts +109 -1
- package/src/tui/completion.js +34 -15
- package/src/tui/composerControls.js +5 -0
- package/src/tui/composerControls.ts +5 -0
- package/src/tui/dialogs.js +5 -2
- package/src/tui/engineSpinner.js +20 -0
- package/src/tui/engineSpinner.ts +46 -0
- package/src/tui/layout.js +1 -1
- package/src/tui/layout.ts +1 -1
- package/src/tui/lineEditor.js +44 -12
- package/src/tui/messageInteraction.js +16 -5
- package/src/tui/messageInteraction.ts +14 -5
- package/src/tui/observerPicker.js +319 -0
- package/src/tui/observerPicker.ts +382 -0
- package/src/tui/prompt.js +247 -55
- package/src/tui/runningLight.js +213 -0
- package/src/tui/runningLight.ts +271 -0
- package/src/tui/sessionSidebar.js +7 -1
- package/src/tui/sessionSidebar.ts +7 -1
- package/src/tui/stage.js +4 -4
- package/src/tui/stageSurface.js +27 -10
- package/src/tui/statusLine.js +27 -4
- package/src/tui/statusLine.ts +27 -4
- package/src/tui/theme.js +5 -2
- package/src/tui/thinkingBox.js +41 -10
- package/src/tui/thinkingBox.ts +43 -10
- package/src/tui/turnRail.js +155 -24
- package/src/tui/turnRail.ts +170 -22
- 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
|
@@ -76,7 +76,24 @@ function splitCommandSegments(command) {
|
|
|
76
76
|
segments.push(current.trim());
|
|
77
77
|
return segments;
|
|
78
78
|
}
|
|
79
|
-
const
|
|
79
|
+
const READ_ONLY_CMD_PATTERNS = [
|
|
80
|
+
String.raw `^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
|
|
81
|
+
String.raw `(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
|
|
82
|
+
String.raw `mvn\s+(?:test\S*|verify\S*)\b`,
|
|
83
|
+
String.raw `git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
|
|
84
|
+
String.raw `npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b`,
|
|
85
|
+
String.raw `pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
|
|
86
|
+
String.raw `yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
|
|
87
|
+
String.raw `bun\s+(?:test|pm)\b`,
|
|
88
|
+
String.raw `npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b`,
|
|
89
|
+
String.raw `tsc\s+--noEmit\b`,
|
|
90
|
+
String.raw `node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))`,
|
|
91
|
+
String.raw `(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))`,
|
|
92
|
+
String.raw `cargo\s+(?:test|check)\b`,
|
|
93
|
+
String.raw `go\s+test\b`,
|
|
94
|
+
String.raw `curl\s+(?:-I|-sI|-s\b|--head)\b`
|
|
95
|
+
];
|
|
96
|
+
const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
|
|
80
97
|
export function isReadOnlyShellCommand(command) {
|
|
81
98
|
const trimmed = command.trim();
|
|
82
99
|
if (!trimmed)
|
package/src/decisionPolicy.ts
CHANGED
|
@@ -109,7 +109,24 @@ function splitCommandSegments(command: string): string[] {
|
|
|
109
109
|
return segments;
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
const
|
|
112
|
+
const READ_ONLY_CMD_PATTERNS = [
|
|
113
|
+
String.raw`^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
|
|
114
|
+
String.raw`(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
|
|
115
|
+
String.raw`mvn\s+(?:test\S*|verify\S*)\b`,
|
|
116
|
+
String.raw`git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
|
|
117
|
+
String.raw`npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b`,
|
|
118
|
+
String.raw`pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
|
|
119
|
+
String.raw`yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
|
|
120
|
+
String.raw`bun\s+(?:test|pm)\b`,
|
|
121
|
+
String.raw`npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b`,
|
|
122
|
+
String.raw`tsc\s+--noEmit\b`,
|
|
123
|
+
String.raw`node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))`,
|
|
124
|
+
String.raw`(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))`,
|
|
125
|
+
String.raw`cargo\s+(?:test|check)\b`,
|
|
126
|
+
String.raw`go\s+test\b`,
|
|
127
|
+
String.raw`curl\s+(?:-I|-sI|-s\b|--head)\b`
|
|
128
|
+
];
|
|
129
|
+
const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
|
|
113
130
|
|
|
114
131
|
export function isReadOnlyShellCommand(command: string): boolean {
|
|
115
132
|
const trimmed = command.trim();
|
|
@@ -119,6 +119,32 @@ export function normalizePeerPlanEntries(value) {
|
|
|
119
119
|
}
|
|
120
120
|
return { explanation, plan: steps };
|
|
121
121
|
}
|
|
122
|
+
const TOOL_CALL_ENVELOPE_KEYS = new Set(['name', 'tool', 'function', 'type', 'id', 'call_id', 'tool_call_id']);
|
|
123
|
+
/**
|
|
124
|
+
* Resolve the argument payload of a text-delimited tool call envelope.
|
|
125
|
+
*
|
|
126
|
+
* Accepts `arguments`, `parameters`, `input`, `args`, nested `function.arguments`,
|
|
127
|
+
* and the flat form some peers emit, where arguments sit beside `name`
|
|
128
|
+
* (`{"name":"update_plan","plan":[...]}`). Falling back to `{}` for the flat form
|
|
129
|
+
* discarded every argument and produced false "is required" validation errors.
|
|
130
|
+
*/
|
|
131
|
+
export function resolveToolCallEnvelopeArguments(parsed) {
|
|
132
|
+
const fnObj = parsed.function && typeof parsed.function === 'object' && !Array.isArray(parsed.function)
|
|
133
|
+
? parsed.function
|
|
134
|
+
: null;
|
|
135
|
+
for (const key of ['arguments', 'parameters', 'input', 'args']) {
|
|
136
|
+
if (parsed[key] !== undefined && parsed[key] !== null)
|
|
137
|
+
return parsed[key];
|
|
138
|
+
}
|
|
139
|
+
if (fnObj && fnObj.arguments !== undefined && fnObj.arguments !== null)
|
|
140
|
+
return fnObj.arguments;
|
|
141
|
+
const flat = {};
|
|
142
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
143
|
+
if (!TOOL_CALL_ENVELOPE_KEYS.has(key))
|
|
144
|
+
flat[key] = value;
|
|
145
|
+
}
|
|
146
|
+
return flat;
|
|
147
|
+
}
|
|
122
148
|
export function extractToolCallJsonObjects(text, allowUnclosedHealing = true) {
|
|
123
149
|
const results = [];
|
|
124
150
|
if (!text || typeof text !== 'string')
|
|
@@ -127,6 +127,31 @@ export function normalizePeerPlanEntries(value: unknown): PlanUpdate | null {
|
|
|
127
127
|
return { explanation, plan: steps };
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
const TOOL_CALL_ENVELOPE_KEYS = new Set(['name', 'tool', 'function', 'type', 'id', 'call_id', 'tool_call_id']);
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Resolve the argument payload of a text-delimited tool call envelope.
|
|
134
|
+
*
|
|
135
|
+
* Accepts `arguments`, `parameters`, `input`, `args`, nested `function.arguments`,
|
|
136
|
+
* and the flat form some peers emit, where arguments sit beside `name`
|
|
137
|
+
* (`{"name":"update_plan","plan":[...]}`). Falling back to `{}` for the flat form
|
|
138
|
+
* discarded every argument and produced false "is required" validation errors.
|
|
139
|
+
*/
|
|
140
|
+
export function resolveToolCallEnvelopeArguments(parsed: Record<string, unknown>): unknown {
|
|
141
|
+
const fnObj = parsed.function && typeof parsed.function === 'object' && !Array.isArray(parsed.function)
|
|
142
|
+
? (parsed.function as Record<string, unknown>)
|
|
143
|
+
: null;
|
|
144
|
+
for (const key of ['arguments', 'parameters', 'input', 'args'] as const) {
|
|
145
|
+
if (parsed[key] !== undefined && parsed[key] !== null) return parsed[key];
|
|
146
|
+
}
|
|
147
|
+
if (fnObj && fnObj.arguments !== undefined && fnObj.arguments !== null) return fnObj.arguments;
|
|
148
|
+
const flat: Record<string, unknown> = {};
|
|
149
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
150
|
+
if (!TOOL_CALL_ENVELOPE_KEYS.has(key)) flat[key] = value;
|
|
151
|
+
}
|
|
152
|
+
return flat;
|
|
153
|
+
}
|
|
154
|
+
|
|
130
155
|
export function extractToolCallJsonObjects(text: string, allowUnclosedHealing = true): Array<Record<string, unknown>> {
|
|
131
156
|
const results: Array<Record<string, unknown>> = [];
|
|
132
157
|
if (!text || typeof text !== 'string') return results;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { auditLog } from '../auditLog.js';
|
|
4
5
|
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
@@ -22,7 +23,8 @@ const DEFAULT_CONFIG = {
|
|
|
22
23
|
const COMPLETION_CLAIMS = [
|
|
23
24
|
/\b(?:done|finished|complete(?:d)?|implemented|resolved|fixed|ready)\b/i,
|
|
24
25
|
/\b(?:all|everything)\b[^.\n]{0,60}\b(?:works?|pass(?:es|ed|ing)?|fixed|done|clean)\b/i,
|
|
25
|
-
/\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i
|
|
26
|
+
/\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i,
|
|
27
|
+
/\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i
|
|
26
28
|
];
|
|
27
29
|
const HONEST_CAVEATS = [
|
|
28
30
|
/\b(?:not|never)\s+(?:run|ran|tested|verified|checked|completed?)\b/i,
|
|
@@ -62,6 +64,9 @@ function boundedTimeout(value) {
|
|
|
62
64
|
return Math.max(200, Math.min(5000, Math.round(value)));
|
|
63
65
|
}
|
|
64
66
|
function safeConfigPath() {
|
|
67
|
+
if (process.env.NODE_TEST_CONTEXT) {
|
|
68
|
+
return path.join(os.tmpdir(), `causyne-test-observer-${process.pid}.json`);
|
|
69
|
+
}
|
|
65
70
|
return CONFIG_FILE;
|
|
66
71
|
}
|
|
67
72
|
function readStoredConfig() {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { auditLog } from '../auditLog.js';
|
|
4
5
|
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
@@ -81,7 +82,8 @@ const DEFAULT_CONFIG: ObserverConfig = {
|
|
|
81
82
|
const COMPLETION_CLAIMS = [
|
|
82
83
|
/\b(?:done|finished|complete(?:d)?|implemented|resolved|fixed|ready)\b/i,
|
|
83
84
|
/\b(?:all|everything)\b[^.\n]{0,60}\b(?:works?|pass(?:es|ed|ing)?|fixed|done|clean)\b/i,
|
|
84
|
-
/\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i
|
|
85
|
+
/\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i,
|
|
86
|
+
/\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i
|
|
85
87
|
];
|
|
86
88
|
|
|
87
89
|
const HONEST_CAVEATS = [
|
|
@@ -122,6 +124,9 @@ function boundedTimeout(value: unknown): number | null {
|
|
|
122
124
|
}
|
|
123
125
|
|
|
124
126
|
function safeConfigPath(): string {
|
|
127
|
+
if (process.env.NODE_TEST_CONTEXT) {
|
|
128
|
+
return path.join(os.tmpdir(), `causyne-test-observer-${process.pid}.json`);
|
|
129
|
+
}
|
|
125
130
|
return CONFIG_FILE;
|
|
126
131
|
}
|
|
127
132
|
|