everydaytok commited on
Commit
0aa7e3f
·
verified ·
1 Parent(s): ccfa574

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +269 -321
app.js CHANGED
@@ -9,16 +9,15 @@ import { createClient } from '@supabase/supabase-js';
9
  // ==========================================
10
  const PORT = 7860;
11
  const SUPABASE_URL = process.env.SUPABASE_URL;
12
- const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY; // Must be Service Role
13
- const REMOTE_SERVER_URL = process.env.REMOTE_AI_URL || "http://localhost:7860";
14
  const FRONT_URL = process.env.FRONT_URL;
 
 
15
 
16
  // --- MODEL CONFIGURATION ---
17
- // Define your specific model IDs here.
18
- // 'Architect': Used for PRDs, Briefings, Complex Reasoning.
19
- // 'Analyst': Used for raw log ingestion, MCP forwarding, and fast tasks.
20
- const SMART_MODEL_ID = "claude";
21
- const FAST_MODEL_ID = "gpt-5-mini"; // or "gpt-4o-mini"
22
 
23
  if (!SUPABASE_URL || !SUPABASE_KEY) {
24
  console.error("FATAL: Missing Supabase URL or Service Key.");
@@ -28,88 +27,71 @@ if (!SUPABASE_URL || !SUPABASE_KEY) {
28
  const app = express();
29
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
30
 
31
- // Increase limit to handle large file contexts/images
32
  app.use(express.json({ limit: '50mb' }));
33
  app.use(cors());
34
 
35
  // ==========================================
36
  // 2. PROMPT MANAGEMENT
37
  // ==========================================
38
- let prompts = {
39
- director_system_prompt: "You are MOMENTUM, an elite AI Project Director. Your goal is to maintain flow.\n\nCOMMANDS:\n1. <thrust_create>{\"title\": \"...\", \"markdown_content\": \"...\", \"tasks\": [\"...\"]}</thrust_create>\n2. <timeline_log>{\"title\": \"...\", \"type\": \"feature\", \"description\": \"...\"}</timeline_log>\n3. <notification>Message</notification>\n4. <update_requirements>Markdown Content</update_requirements>\n\nOutput commands mixed with natural language.",
40
- init_system_prompt: "You are the Lead Architect. Initialize this project.\n1. Analyze the user's idea.\n2. Create a comprehensive Requirements Document (Markdown).\n3. Create the FIRST Thrust (Briefing) to set up the environment.\n\nOUTPUT FORMAT:\nWrap the Requirements doc in <update_requirements>...</update_requirements> tags.\nWrap the First Thrust in <thrust_create>...</thrust_create> tags.",
41
- log_analyst_prompt: "You are a Log Ingestion Analyst. Analyze the provided raw logs or MCP data. Summarize critical errors, performance bottlenecks, or notable events. Be concise."
42
- };
43
-
44
  try {
45
  const promptsPath = path.resolve('./prompts.json');
46
  if (fs.existsSync(promptsPath)) {
47
- console.log("Loading custom prompts from prompts.json...");
48
  const fileData = fs.readFileSync(promptsPath, 'utf8');
49
- const parsed = JSON.parse(fileData);
50
- prompts = { ...prompts, ...parsed };
 
 
51
  }
52
  } catch (e) {
53
- console.error("Prompt Load Error (Using Defaults):", e.message);
 
54
  }
55
 
56
  // ==========================================
57
- // 3. STATE MANAGER (Full Implementation)
58
  // ==========================================
59
  const activeProjects = new Map();
60
 
61
  const StateManager = {
62
- /**
63
- * Fetches chat history, using in-memory cache if available/fresh,
64
- * otherwise pulling from Supabase 'message_chunks'.
65
- */
66
  getHistory: async (projectId) => {
67
- // Cache Hit
68
  if (activeProjects.has(projectId)) {
69
  const cached = activeProjects.get(projectId);
70
  cached.lastActive = Date.now();
71
  return cached.history;
72
  }
73
 
74
- // Cache Miss - DB Fetch
75
  const { data: chunks, error } = await supabase
76
  .from('message_chunks')
77
  .select('*')
78
  .eq('project_id', projectId)
79
  .order('chunk_index', { ascending: false })
80
- .limit(10); // Load last 10 chunks (~200 messages max)
81
 
82
- if (error) {
83
- console.error(`[StateManager] DB Fetch Error for ${projectId}:`, error.message);
84
- return [];
85
- }
86
-
87
- // Flatten chunks (Newest chunks are first, so reverse to get chronological)
88
  const fullHistory = (chunks || []).reverse().flatMap(c => c.payload || []);
89
-
90
- // Hydrate Cache
91
- activeProjects.set(projectId, { history: fullHistory, lastActive: Date.now() });
92
  return fullHistory;
93
  },
94
 
95
- /**
96
- * Appends a message to the history.
97
- * Handles the Chunking Logic: Appends to latest chunk if <20 msgs, else creates new.
98
- */
99
  addHistory: async (projectId, role, text) => {
100
  const newMessage = { role, parts: [{ text }] };
101
 
102
- // 1. Update In-Memory Cache
103
  if (activeProjects.has(projectId)) {
104
  const project = activeProjects.get(projectId);
105
  project.history.push(newMessage);
106
  project.lastActive = Date.now();
 
 
107
  }
108
 
109
- // 2. Sync to Supabase
110
  try {
111
- // Get the absolute latest chunk
112
- const { data: latestData, error: fetchError } = await supabase
113
  .from('message_chunks')
114
  .select('id, chunk_index, payload')
115
  .eq('project_id', projectId)
@@ -117,393 +99,359 @@ const StateManager = {
117
  .limit(1)
118
  .single();
119
 
120
- if (fetchError && fetchError.code !== 'PGRST116') { // Ignore "No Rows Found" error
121
- console.error("[StateManager] Chunk Fetch Error:", fetchError.message);
122
- }
123
-
124
- const latestChunk = latestData;
125
- const currentPayload = (latestChunk && Array.isArray(latestChunk.payload)) ? latestChunk.payload : [];
126
 
127
  if (latestChunk && currentPayload.length < 20) {
128
- // APPEND to existing chunk
129
- const updatedPayload = [...currentPayload, newMessage];
130
- const { error: updateError } = await supabase
131
- .from('message_chunks')
132
- .update({ payload: updatedPayload })
133
- .eq('id', latestChunk.id);
134
-
135
- if (updateError) console.error("[StateManager] Chunk Update Failed:", updateError.message);
136
  } else {
137
- // CREATE NEW chunk
138
- const nextIndex = (latestChunk?.chunk_index ?? -1) + 1;
139
- const { error: insertError } = await supabase
140
- .from('message_chunks')
141
- .insert({
142
- project_id: projectId, // This maps to 'lead_id' in your schema logic, ensure column matches
143
- lead_id: projectId, // Explicitly setting lead_id based on your schema reqs
144
- chunk_index: nextIndex,
145
- payload: [newMessage]
146
- });
147
-
148
- if (insertError) console.error("[StateManager] Chunk Insert Failed:", insertError.message);
149
  }
150
- } catch (e) {
151
- console.error("[StateManager] Critical Logic Error:", e);
152
- }
153
- },
154
 
155
- /**
156
- * Garbage Collector
157
- */
158
- cleanup: () => {
159
- const now = Date.now();
160
- const TTL = 4 * 60 * 60 * 1000; // 4 Hours
161
- let count = 0;
162
- for (const [id, data] of activeProjects.entries()) {
163
- if (now - data.lastActive > TTL) {
164
- activeProjects.delete(id);
165
- count++;
166
  }
167
- }
168
- if (count > 0) console.log(`[StateManager] 🧹 GC cleaned ${count} idle projects.`);
 
 
 
 
 
 
 
 
 
 
 
 
169
  }
170
  };
171
 
172
- // Run GC every hour
173
- setInterval(StateManager.cleanup, 60 * 60 * 1000);
174
-
175
  // ==========================================
176
- // 4. AI ENGINE & CONTEXT LOGIC
177
  // ==========================================
178
 
179
- const flattenHistory = (history, currentInput, systemPrompt, limit = 10, projectContext = "") => {
180
- // Only take last 'limit' messages for context window to save tokens
181
- const recentHistory = history ? history.slice(-limit) : [];
182
-
183
- let contextStr = recentHistory.map(m => {
184
- const roleName = m.role === 'model' ? 'Assistant' : 'User';
185
- const content = m.parts?.[0]?.text || m.content || "";
186
- return `${roleName}: ${content}`;
187
- }).join('\n');
188
 
189
- // Robust prompt construction
190
- return `System: ${systemPrompt}\n\n${projectContext}\n\n[CHAT HISTORY]:\n${contextStr}\n\nUser: ${currentInput}\nAssistant:`;
191
- };
192
 
193
- /**
194
- * Enhanced callAI function that supports switching Model IDs
195
- */
196
- const callAI = async (history, input, contextData, systemPromptOverride = null, projectContext = "", targetModelId = SMART_MODEL_ID) => {
197
- const systemPrompt = systemPromptOverride || prompts.director_system_prompt;
198
 
199
- // Serialize Context safely
200
- let contextString = "";
201
  try {
202
- contextString = JSON.stringify(contextData, null, 2);
203
- } catch (e) {
204
- contextString = "Error serializing context data.";
205
- }
206
-
207
- const enrichedInput = `[CURRENT WORKSPACE CONTEXT]:\n${contextString}\n\n[USER INPUT]: ${input}`;
208
- const prompt = flattenHistory(history, enrichedInput, systemPrompt, 10, projectContext);
209
-
210
- try {
211
- console.log(`[AI] Calling Remote Engine at ${REMOTE_SERVER_URL}...`);
212
- console.log(`[AI] Selected Model: ${targetModelId}`);
213
-
214
  const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
215
  method: 'POST',
216
  headers: { 'Content-Type': 'application/json' },
217
- body: JSON.stringify({
218
- model: targetModelId, // DYNAMIC MODEL ID INJECTION
219
- prompt: prompt,
220
- system_prompt: systemPrompt
221
- })
222
  });
223
 
224
- if (!response.ok) {
225
- const errText = await response.text();
226
- throw new Error(`Remote AI Status ${response.status}: ${errText}`);
227
- }
228
-
229
  const result = await response.json();
230
- const text = result.data || result.text || result.content || "";
231
- const usage = result.usage || { totalTokenCount: 0 };
232
-
233
- return { text, usage };
234
-
235
  } catch (e) {
236
- console.error("[AI] Connection Failed:", e.message);
237
- return { text: "<notification>AI Connection Failed. Check Backend Logs.</notification>", usage: {} };
238
  }
239
  };
240
 
241
  // ==========================================
242
- // 5. COMMAND PARSER & EXECUTOR
243
  // ==========================================
244
 
245
  function extractCommands(text) {
246
  const commands = [];
247
-
248
- // Helper to safely parse JSON from XML-like tags
249
- const parse = (regex, type) => {
250
  let match;
251
- // Reset regex state just in case
252
  regex.lastIndex = 0;
253
  while ((match = regex.exec(text)) !== null) {
254
  try {
255
- // If it's a notification, payload is string. Else JSON.
256
- if (type === 'notification' || type === 'update_requirements') {
257
- commands.push({ type, payload: match[1].trim() });
258
- } else {
259
- commands.push({ type, payload: JSON.parse(match[1]) });
260
- }
261
- } catch (e) {
262
- console.error(`[Parser] JSON Error in ${type}:`, e.message);
263
- }
264
  }
265
  };
266
 
267
  parse(/<thrust_create>([\s\S]*?)<\/thrust_create>/g, 'create_thrust');
268
  parse(/<timeline_log>([\s\S]*?)<\/timeline_log>/g, 'log_timeline');
269
- parse(/<notification>([\s\S]*?)<\/notification>/g, 'notification');
270
- parse(/<update_requirements>([\s\S]*?)<\/update_requirements>/g, 'update_requirements');
 
 
 
271
 
272
  return commands;
273
  }
274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  async function executeCommands(userId, projectId, commands) {
276
- let shouldReload = false;
277
 
278
  for (const cmd of commands) {
279
- console.log(`[Executor] Processing command: ${cmd.type}`);
 
280
  try {
281
- // 1. Create Thrust (Briefing)
282
  if (cmd.type === 'create_thrust') {
283
- const { data: thrust, error } = await supabase.from('thrusts').insert({
284
  lead_id: projectId,
285
  title: cmd.payload.title,
286
  markdown_content: cmd.payload.markdown_content,
287
  status: 'active'
288
  }).select().single();
289
 
290
- if (error) throw new Error(`Thrust Insert: ${error.message}`);
291
-
292
- if (thrust && cmd.payload.tasks && Array.isArray(cmd.payload.tasks)) {
293
  const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
294
- if (tasks.length > 0) {
295
- const { error: taskError } = await supabase.from('thrust_tasks').insert(tasks);
296
- if (taskError) console.error("Thrust Task Error:", taskError.message);
297
- }
298
  }
299
- shouldReload = true;
300
  }
301
 
302
- // 2. Log Timeline
303
  if (cmd.type === 'log_timeline') {
304
- const { error } = await supabase.from('timeline_events').insert({
305
  lead_id: projectId,
306
  title: cmd.payload.title,
307
  description: cmd.payload.description,
308
  type: (cmd.payload.type || 'system').toLowerCase(),
309
  });
310
- if (error) console.error("Timeline Error:", error.message);
311
- shouldReload = true;
312
  }
313
 
314
- // 3. Update Requirements Doc
315
  if (cmd.type === 'update_requirements') {
316
- const { error } = await supabase.from('leads').update({
317
- requirements_doc: cmd.payload
318
- }).eq('id', projectId);
319
 
320
- if (error) console.error("PRD Update Error:", error.message);
321
- shouldReload = true; // Reload so context is fresh
 
 
 
 
 
 
 
 
 
 
 
322
  }
323
 
324
- // 4. Notify Frontend via Gateway
325
  if (cmd.type === 'notification' && FRONT_URL) {
326
- // Fire and forget
327
  fetch(`${FRONT_URL}/internal/notify`, {
328
  method: 'POST',
329
  headers: { 'Content-Type': 'application/json' },
330
- body: JSON.stringify({
331
- user_id: userId,
332
- type: 'toast',
333
- message: cmd.payload
334
- })
335
- }).catch(e => console.error("Gateway Notify Error:", e.message));
336
  }
337
 
338
- } catch (err) {
339
- console.error(`[Executor] Failed to execute ${cmd.type}:`, err.message);
340
- }
341
  }
342
- return shouldReload;
343
  }
344
 
345
  // ==========================================
346
  // 6. ENDPOINTS
347
  // ==========================================
348
 
349
- app.get('/', (req, res) => res.send('Core Context Brain Active'));
350
-
351
- // --- Endpoint: Initialize Project (Background Architect) ---
352
- // USES: SMART_MODEL_ID
353
  app.post('/init-project', async (req, res) => {
354
  const { userId, name, description, localPath } = req.body;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
- if (!userId || !name) {
357
- return res.status(400).json({ error: "Missing required fields" });
358
- }
359
-
360
- console.log(`🚀 Initializing Project: ${name} (${userId})`);
361
-
362
- try {
363
- // A. Create Lead in DB
364
- const { data: lead, error } = await supabase.from('leads').insert({
365
- user_id: userId,
366
- name,
367
- description,
368
- local_path: localPath,
369
- status: 'active',
370
- requirements_doc: "Initializing..."
371
- }).select().single();
372
-
373
- if (error) throw error;
374
 
375
- // B. Send HTTP Response immediately (Async processing)
376
- res.json({ success: true, leadId: lead.id, message: "Project created. AI is Architecting..." });
377
 
378
- // C. Background Operation
379
- setImmediate(async () => {
380
- console.log(`[Init] Starting AI Architecture for ${lead.id}...`);
381
- const initInput = `PROJECT NAME: ${name}\nDESCRIPTION: ${description}\n\nTask: Initialize structure, create PRD, and first Thrust.`;
382
 
383
- // 1. Call AI with INIT Prompt AND Smart Model
384
- const aiResult = await callAI([], initInput, {}, prompts.init_system_prompt, "", SMART_MODEL_ID);
 
 
 
 
 
 
 
 
385
 
386
- // 2. Add this interaction to history so the project has a "start"
387
- await StateManager.addHistory(lead.id, 'user', initInput);
388
- await StateManager.addHistory(lead.id, 'model', aiResult.text);
 
389
 
390
- // 3. Execute (Save PRD, Create Thrust)
391
- const commands = extractCommands(aiResult.text);
392
- await executeCommands(userId, lead.id, commands);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
 
394
- console.log(`[Init] Architecture complete for ${lead.id}. Commands executed: ${commands.length}`);
 
395
 
396
- // 4. Notify User
397
- if (FRONT_URL) {
398
- fetch(`${FRONT_URL}/internal/notify`, {
399
- method: 'POST',
400
- headers: { 'Content-Type': 'application/json' },
401
- body: JSON.stringify({
402
- user_id: userId,
403
- type: 'reload_project',
404
- message: "Project Architecture Ready"
405
- })
406
- }).catch(e => console.error("Init Notify Failed", e.message));
407
- }
408
- });
409
 
410
  } catch (e) {
411
- console.error("Init Error:", e);
412
- if (!res.headersSent) res.status(500).json({ error: e.message });
413
  }
414
  });
415
 
416
- // --- Endpoint: Process Chat & Logs (Context Aware) ---
417
- // USES: DYNAMIC MODEL (Architect or Analyst)
418
- app.post('/process', async (req, res) => {
419
- // task_type can be 'chat' (default) or 'log_ingestion'
420
- const { userId, projectId, prompt, context, task_type = 'chat' } = req.body;
421
-
422
- if (!userId || !projectId || !prompt) {
423
- return res.status(400).json({ error: "Missing required fields" });
424
- }
425
-
426
- // --- SELECTION LOGIC ---
427
- // Log ingestion uses the FAST model. High-level planning uses the SMART model.
428
- const selectedModelId = task_type === 'log_ingestion' ? FAST_MODEL_ID : SMART_MODEL_ID;
429
- const systemPromptOverride = task_type === 'log_ingestion' ? prompts.log_analyst_prompt : null;
430
-
431
- console.log(`🧠 Processing for ${projectId} (Type: ${task_type} -> Model: ${selectedModelId})`);
432
 
433
  try {
434
- // A. Fetch Context (PRD + Timeline)
435
- // We fetch these fresh every time to ensure the AI has the "God View"
436
- const { data: lead } = await supabase.from('leads')
437
- .select('requirements_doc')
438
- .eq('id', projectId)
439
- .single();
440
-
441
- const { data: timeline } = await supabase.from('timeline_events')
442
- .select('title, type, description, created_at')
443
  .eq('lead_id', projectId)
444
  .order('created_at', { ascending: false })
445
- .limit(5);
 
446
 
447
- const projectContext = `
448
- [PROJECT REQUIREMENTS DOCUMENT]:
449
- ${lead?.requirements_doc || "No requirements set yet."}
450
 
451
- [RECENT TIMELINE EVENTS]:
452
- ${JSON.stringify(timeline || [])}
453
- `;
 
 
 
 
 
 
454
 
455
- // B. State Management: Fetch History & Add User Input
456
- // If it's a huge log dump, we might NOT want to pollute history, but assuming we do for now:
 
 
 
 
 
457
  const history = await StateManager.getHistory(projectId);
458
- await StateManager.addHistory(projectId, 'user', prompt);
459
-
460
- // C. AI Generation (Pass selected Model ID)
461
- const aiResult = await callAI(history, prompt, context, systemPromptOverride, projectContext, selectedModelId);
462
- const rawText = aiResult.text;
463
-
464
- // D. State Management: Add AI Response
465
- await StateManager.addHistory(projectId, 'model', rawText);
466
-
467
- // E. Execute Commands (Only relevant if model returns commands, usually Smart model)
468
- const commands = extractCommands(rawText);
469
- const shouldReload = await executeCommands(userId, projectId, commands);
470
-
471
- // F. Clean Response (Remove XML tags for frontend display)
472
- const cleanText = rawText
473
- .replace(/<thrust_create>[\s\S]*?<\/thrust_create>/g, '')
474
- .replace(/<timeline_log>[\s\S]*?<\/timeline_log>/g, '')
475
- .replace(/<notification>[\s\S]*?<\/notification>/g, '')
476
- .replace(/<update_requirements>[\s\S]*?<\/update_requirements>/g, '')
477
- .trim();
478
-
479
- res.json({
480
- text: cleanText,
481
- should_reload: shouldReload,
482
- usage: aiResult.usage,
483
- model_used: selectedModelId
484
- });
485
 
486
  } catch (e) {
487
- console.error("Process Error:", e);
488
- res.status(500).json({ error: "Processing Failed" });
489
  }
490
  });
491
 
492
- // --- New Endpoint: Dedicated Log Ingestion (Optional helper) ---
493
- app.post('/ingest-logs', async (req, res) => {
494
- // Wraps /process with enforced type
495
- req.body.task_type = 'log_ingestion';
496
- // Forward internally logic would go here, but usually, clients just call /process with flag
497
- // This is just a placeholder if you need a specific route for webhooks.
498
- res.redirect(307, '/process');
499
- });
500
-
501
- // ==========================================
502
- // 7. BOOT
503
- // ==========================================
504
- app.listen(PORT, () => {
505
- console.log(`✅ Core Server is Online on Port ${PORT}`);
506
- console.log(`🔗 Remote AI: ${REMOTE_SERVER_URL}`);
507
- console.log(`🤖 Models Configured: Smart=${SMART_MODEL_ID}, Fast=${FAST_MODEL_ID}`);
508
- console.log(`🔗 Front Gateway: ${FRONT_URL || "Not Set"}`);
509
- });
 
9
  // ==========================================
10
  const PORT = 7860;
11
  const SUPABASE_URL = process.env.SUPABASE_URL;
12
+ const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
13
+ const REMOTE_SERVER_URL = process.env.REMOTE_AI_URL || "http://localhost:11434"; // Defaulting to local Ollama/LMStudio if env missing
14
  const FRONT_URL = process.env.FRONT_URL;
15
+ const CRON_REGISTRY_URL = process.env.CRON_REGISTRY_URL || "http://localhost:7861"; // URL of the Cron Server
16
+ const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
17
 
18
  // --- MODEL CONFIGURATION ---
19
+ const SMART_MODEL_ID = "gpt-4-turbo";
20
+ const FAST_MODEL_ID = "gpt-3.5-turbo";
 
 
 
21
 
22
  if (!SUPABASE_URL || !SUPABASE_KEY) {
23
  console.error("FATAL: Missing Supabase URL or Service Key.");
 
27
  const app = express();
28
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
29
 
 
30
  app.use(express.json({ limit: '50mb' }));
31
  app.use(cors());
32
 
33
  // ==========================================
34
  // 2. PROMPT MANAGEMENT
35
  // ==========================================
36
+ let prompts = {};
37
+ // Load synchronously on boot
 
 
 
 
38
  try {
39
  const promptsPath = path.resolve('./prompts.json');
40
  if (fs.existsSync(promptsPath)) {
 
41
  const fileData = fs.readFileSync(promptsPath, 'utf8');
42
+ prompts = JSON.parse(fileData);
43
+ console.log("✅ Prompts loaded.");
44
+ } else {
45
+ throw new Error("prompts.json not found");
46
  }
47
  } catch (e) {
48
+ console.error("❌ Prompt Load Error:", e.message);
49
+ process.exit(1);
50
  }
51
 
52
  // ==========================================
53
+ // 3. STATE MANAGER
54
  // ==========================================
55
  const activeProjects = new Map();
56
 
57
  const StateManager = {
 
 
 
 
58
  getHistory: async (projectId) => {
 
59
  if (activeProjects.has(projectId)) {
60
  const cached = activeProjects.get(projectId);
61
  cached.lastActive = Date.now();
62
  return cached.history;
63
  }
64
 
 
65
  const { data: chunks, error } = await supabase
66
  .from('message_chunks')
67
  .select('*')
68
  .eq('project_id', projectId)
69
  .order('chunk_index', { ascending: false })
70
+ .limit(10);
71
 
72
+ if (error) return [];
 
 
 
 
 
73
  const fullHistory = (chunks || []).reverse().flatMap(c => c.payload || []);
74
+
75
+ // Initialize Cache with default frozen state (false) if not known, will update from DB later
76
+ activeProjects.set(projectId, { history: fullHistory, lastActive: Date.now(), isFrozen: false });
77
  return fullHistory;
78
  },
79
 
 
 
 
 
80
  addHistory: async (projectId, role, text) => {
81
  const newMessage = { role, parts: [{ text }] };
82
 
83
+ // Cache update
84
  if (activeProjects.has(projectId)) {
85
  const project = activeProjects.get(projectId);
86
  project.history.push(newMessage);
87
  project.lastActive = Date.now();
88
+ // User activity unfreezes project automatically
89
+ if (role === 'user') project.isFrozen = false;
90
  }
91
 
92
+ // DB Sync (Chunking Logic)
93
  try {
94
+ const { data: latestChunk } = await supabase
 
95
  .from('message_chunks')
96
  .select('id, chunk_index, payload')
97
  .eq('project_id', projectId)
 
99
  .limit(1)
100
  .single();
101
 
102
+ const currentPayload = (latestChunk?.payload) || [];
 
 
 
 
 
103
 
104
  if (latestChunk && currentPayload.length < 20) {
105
+ await supabase.from('message_chunks').update({
106
+ payload: [...currentPayload, newMessage]
107
+ }).eq('id', latestChunk.id);
 
 
 
 
 
108
  } else {
109
+ await supabase.from('message_chunks').insert({
110
+ project_id: projectId,
111
+ lead_id: projectId,
112
+ chunk_index: (latestChunk?.chunk_index ?? -1) + 1,
113
+ payload: [newMessage]
114
+ });
 
 
 
 
 
 
115
  }
 
 
 
 
116
 
117
+ // If user spoke, unfreeze in DB
118
+ if (role === 'user') {
119
+ await supabase.from('leads').update({ is_frozen: false }).eq('id', projectId);
 
 
 
 
 
 
 
 
120
  }
121
+
122
+ } catch (e) { console.error("History Sync Error", e); }
123
+ },
124
+
125
+ // Check frozen state from DB
126
+ isFrozen: async (projectId) => {
127
+ if (activeProjects.has(projectId)) return activeProjects.get(projectId).isFrozen;
128
+ const { data } = await supabase.from('leads').select('is_frozen').eq('id', projectId).single();
129
+ return data?.is_frozen || false;
130
+ },
131
+
132
+ setFrozen: async (projectId, status) => {
133
+ if (activeProjects.has(projectId)) activeProjects.get(projectId).isFrozen = status;
134
+ await supabase.from('leads').update({ is_frozen: status }).eq('id', projectId);
135
  }
136
  };
137
 
 
 
 
138
  // ==========================================
139
+ // 4. AI ENGINE
140
  // ==========================================
141
 
142
+ const callAI = async (history, input, contextData, systemPrompt, projectContext, modelId) => {
143
+ // Construct Context
144
+ let contextStr = "";
145
+ try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
 
 
 
 
 
146
 
147
+ const recentHistory = history.slice(-10).map(m =>
148
+ `${m.role === 'model' ? 'Assistant' : 'User'}: ${m.parts?.[0]?.text || ""}`
149
+ ).join('\n');
150
 
151
+ const fullPrompt = `System: ${systemPrompt}\n\n${projectContext}\n\n[HISTORY]:\n${recentHistory}\n\n[CONTEXT]: ${contextStr}\n\nUser: ${input}\nAssistant:`;
 
 
 
 
152
 
 
 
153
  try {
 
 
 
 
 
 
 
 
 
 
 
 
154
  const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
155
  method: 'POST',
156
  headers: { 'Content-Type': 'application/json' },
157
+ body: JSON.stringify({ model: modelId, prompt: fullPrompt, system_prompt: systemPrompt })
 
 
 
 
158
  });
159
 
160
+ if (!response.ok) throw new Error("AI API Error");
 
 
 
 
161
  const result = await response.json();
162
+ return { text: result.data || result.text || "", usage: result.usage };
 
 
 
 
163
  } catch (e) {
164
+ return { text: "<notification>AI Unreachable</notification>", usage: {} };
 
165
  }
166
  };
167
 
168
  // ==========================================
169
+ // 5. LOGIC & COMMANDS
170
  // ==========================================
171
 
172
  function extractCommands(text) {
173
  const commands = [];
174
+ const parse = (regex, type, isJson = true) => {
 
 
175
  let match;
 
176
  regex.lastIndex = 0;
177
  while ((match = regex.exec(text)) !== null) {
178
  try {
179
+ commands.push({ type, payload: isJson ? JSON.parse(match[1]) : match[1].trim() });
180
+ } catch (e) { console.error(`Parse Error (${type})`, e); }
 
 
 
 
 
 
 
181
  }
182
  };
183
 
184
  parse(/<thrust_create>([\s\S]*?)<\/thrust_create>/g, 'create_thrust');
185
  parse(/<timeline_log>([\s\S]*?)<\/timeline_log>/g, 'log_timeline');
186
+ parse(/<notification>([\s\S]*?)<\/notification>/g, 'notification', false);
187
+ parse(/<update_requirements>([\s\S]*?)<\/update_requirements>/g, 'update_requirements', false);
188
+ parse(/<schedule_briefing>([\s\S]*?)<\/schedule_briefing>/g, 'schedule_briefing');
189
+ parse(/<freeze_project>([\s\S]*?)<\/freeze_project>/g, 'freeze_project', false); // expecting "true"
190
+ parse(/<thrust_complete>([\s\S]*?)<\/thrust_complete>/g, 'thrust_complete', false); // expecting "true"
191
 
192
  return commands;
193
  }
194
 
195
+ // Register Cron Helper
196
+ async function registerMorningCron(projectId, offset) {
197
+ // 1. Calculate time until next 6 AM
198
+ const now = new Date();
199
+ const target = new Date(now);
200
+
201
+ // Adjust logic: Find 6 AM in user's timezone relative to UTC
202
+ // Simple approach: Calculate ms delay
203
+ target.setUTCHours(6 - offset, 0, 0, 0);
204
+
205
+ if (target <= now) {
206
+ // If 6AM passed today, schedule for tomorrow
207
+ target.setDate(target.getDate() + 1);
208
+ }
209
+
210
+ const delayMs = target.getTime() - now.getTime();
211
+ const intervalMs = 24 * 60 * 60 * 1000; // 24 Hours
212
+
213
+ console.log(`⏰ Scheduling Briefing for ${projectId}. Next run in ${(delayMs/1000/60).toFixed(1)} mins.`);
214
+
215
+ // 2. Call Cron Registry (One time set for specific start, then interval)
216
+ // Note: The simple registry provided uses setInterval. To sync to 6AM exactly,
217
+ // we register a job that fires in 'delayMs', which then executes logic and re-registers itself
218
+ // OR simply use 24h interval starting NOW if close enough.
219
+
220
+ // Better strategy for this specific "Morning" requirement with a simple setInterval registry:
221
+ // We register a job with delayMs. The payload tells the Core "Setup Daily Loop".
222
+
223
+ await fetch(`${CRON_REGISTRY_URL}/register`, {
224
+ method: 'POST',
225
+ headers: { 'Content-Type': 'application/json' },
226
+ body: JSON.stringify({
227
+ secret: CRON_SECRET,
228
+ jobId: `briefing_${projectId}`,
229
+ intervalMs: intervalMs,
230
+ webhookUrl: `http://localhost:${PORT}/automated-briefing`, // Self-call
231
+ payload: { projectId, timezoneOffset: offset }
232
+ })
233
+ }).catch(e => console.error("Cron Reg Error", e));
234
+ }
235
+
236
  async function executeCommands(userId, projectId, commands) {
237
+ let flags = { shouldReload: false, thrustComplete: false };
238
 
239
  for (const cmd of commands) {
240
+ console.log(`[CMD] ${cmd.type} -> Project: ${projectId}`);
241
+
242
  try {
 
243
  if (cmd.type === 'create_thrust') {
244
+ const { data: thrust } = await supabase.from('thrusts').insert({
245
  lead_id: projectId,
246
  title: cmd.payload.title,
247
  markdown_content: cmd.payload.markdown_content,
248
  status: 'active'
249
  }).select().single();
250
 
251
+ if (thrust && cmd.payload.tasks) {
 
 
252
  const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
253
+ await supabase.from('thrust_tasks').insert(tasks);
 
 
 
254
  }
255
+ flags.shouldReload = true;
256
  }
257
 
 
258
  if (cmd.type === 'log_timeline') {
259
+ await supabase.from('timeline_events').insert({
260
  lead_id: projectId,
261
  title: cmd.payload.title,
262
  description: cmd.payload.description,
263
  type: (cmd.payload.type || 'system').toLowerCase(),
264
  });
265
+ flags.shouldReload = true;
 
266
  }
267
 
 
268
  if (cmd.type === 'update_requirements') {
269
+ await supabase.from('leads').update({ requirements_doc: cmd.payload }).eq('id', projectId);
270
+ flags.shouldReload = true;
271
+ }
272
 
273
+ if (cmd.type === 'schedule_briefing') {
274
+ const offset = cmd.payload.timezone_offset || 0;
275
+ await registerMorningCron(projectId, offset);
276
+ }
277
+
278
+ if (cmd.type === 'freeze_project') {
279
+ const isFrozen = cmd.payload === 'true';
280
+ await StateManager.setFrozen(projectId, isFrozen);
281
+ console.log(`❄️ Project ${projectId} Frozen: ${isFrozen}`);
282
+ }
283
+
284
+ if (cmd.type === 'thrust_complete') {
285
+ flags.thrustComplete = true; // Signals Core to trigger Smart Model
286
  }
287
 
 
288
  if (cmd.type === 'notification' && FRONT_URL) {
 
289
  fetch(`${FRONT_URL}/internal/notify`, {
290
  method: 'POST',
291
  headers: { 'Content-Type': 'application/json' },
292
+ body: JSON.stringify({ user_id: userId, type: 'toast', message: cmd.payload })
293
+ }).catch(() => {});
 
 
 
 
294
  }
295
 
296
+ } catch (e) { console.error("Exec Error", e); }
 
 
297
  }
298
+ return flags;
299
  }
300
 
301
  // ==========================================
302
  // 6. ENDPOINTS
303
  // ==========================================
304
 
305
+ // --- INIT ---
 
 
 
306
  app.post('/init-project', async (req, res) => {
307
  const { userId, name, description, localPath } = req.body;
308
+
309
+ // Create DB Entry
310
+ const { data: lead } = await supabase.from('leads').insert({
311
+ user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..."
312
+ }).select().single();
313
+
314
+ res.json({ success: true, leadId: lead.id });
315
+
316
+ // Background Process
317
+ setImmediate(async () => {
318
+ const initInput = `PROJECT: ${name}\nDESC: ${description}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
319
+ const aiResult = await callAI([], initInput, {}, prompts.init_system_prompt, "", SMART_MODEL_ID);
320
+
321
+ await StateManager.addHistory(lead.id, 'user', initInput);
322
+ await StateManager.addHistory(lead.id, 'model', aiResult.text);
323
+
324
+ const cmds = extractCommands(aiResult.text);
325
+ await executeCommands(userId, lead.id, cmds);
326
+ });
327
+ });
328
 
329
+ // --- MAIN PROCESS ---
330
+ app.post('/process', async (req, res) => {
331
+ const { userId, projectId, prompt, context, task_type = 'chat' } = req.body;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
 
333
+ // 1. Unfreeze if user interacts
334
+ if (task_type === 'chat') await StateManager.setFrozen(projectId, false);
335
 
336
+ // 2. Select Model
337
+ // Logic: Log ingestion uses Fast model. If Fast model says "Thrust Complete", we switch to Smart.
338
+ let selectedModel = (task_type === 'log_ingestion') ? FAST_MODEL_ID : SMART_MODEL_ID;
339
+ let sysPrompt = (task_type === 'log_ingestion') ? prompts.log_analyst_prompt : prompts.director_system_prompt;
340
 
341
+ try {
342
+ // Fetch Context (PRD + Current Thrust)
343
+ const { data: lead } = await supabase.from('leads').select('requirements_doc').eq('id', projectId).single();
344
+ const { data: activeThrust } = await supabase.from('thrusts')
345
+ .select('title, tasks:thrust_tasks(title, status)')
346
+ .eq('lead_id', projectId)
347
+ .eq('status', 'active')
348
+ .order('created_at', { ascending: false })
349
+ .limit(1)
350
+ .single();
351
 
352
+ const projectContext = `
353
+ [PRD]: ${lead?.requirements_doc?.substring(0, 2000)}...
354
+ [CURRENT THRUST]: ${activeThrust ? JSON.stringify(activeThrust) : "None"}
355
+ `;
356
 
357
+ const history = await StateManager.getHistory(projectId);
358
+ if (task_type === 'chat') await StateManager.addHistory(projectId, 'user', prompt);
359
+
360
+ // 3. AI Execution
361
+ let aiResult = await callAI(history, prompt, context, sysPrompt, projectContext, selectedModel);
362
+
363
+ // 4. Command Execution
364
+ let cmds = extractCommands(aiResult.text);
365
+ let flags = await executeCommands(userId, projectId, cmds);
366
+
367
+ // 5. AUTO-ESCALATION (Fast -> Smart)
368
+ // If Log Analyst says thrust is done, we immediately call the Smart Director to generate the next one.
369
+ if (flags.thrustComplete && task_type === 'log_ingestion') {
370
+ console.log(`🚀 Thrust Complete detected by Analyst. Escalating to Director...`);
371
+
372
+ const escalationPrompt = "The previous thrust is complete based on logs. Generate the next Thrust immediately to keep momentum.";
373
+ // Call Smart Model (No history of logs, just the context that it's done)
374
+ const smartResult = await callAI(history, escalationPrompt, context, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
375
+
376
+ // Append Smart response
377
+ aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
378
+
379
+ const smartCmds = extractCommands(smartResult.text);
380
+ await executeCommands(userId, projectId, smartCmds);
381
+
382
+ // Save history
383
+ await StateManager.addHistory(projectId, 'model', aiResult.text);
384
+ } else {
385
+ await StateManager.addHistory(projectId, 'model', aiResult.text);
386
+ }
387
 
388
+ // Clean output
389
+ const cleanText = aiResult.text.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, '').trim();
390
 
391
+ res.json({ text: cleanText, should_reload: flags.shouldReload });
 
 
 
 
 
 
 
 
 
 
 
 
392
 
393
  } catch (e) {
394
+ console.error(e);
395
+ res.status(500).json({ error: "Processing Error" });
396
  }
397
  });
398
 
399
+ // --- AUTOMATED MORNING BRIEFING (Called by Cron) ---
400
+ app.post('/automated-briefing', async (req, res) => {
401
+ const { projectId } = req.body;
402
+ console.log(`☀️ Morning Briefing Triggered: ${projectId}`);
 
 
 
 
 
 
 
 
 
 
 
 
403
 
404
  try {
405
+ // 1. Check Freeze State
406
+ const isFrozen = await StateManager.isFrozen(projectId);
407
+
408
+ // Check when the last thrust was made. If made today, skip.
409
+ const { data: lastThrust } = await supabase.from('thrusts')
410
+ .select('created_at')
 
 
 
411
  .eq('lead_id', projectId)
412
  .order('created_at', { ascending: false })
413
+ .limit(1)
414
+ .single();
415
 
416
+ const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
417
+ const todayDate = new Date().getDate();
 
418
 
419
+ // LOGIC: If frozen, DO NOT generate. If thrust made today, DO NOT generate.
420
+ if (isFrozen) {
421
+ console.log(`Skipping briefing: Project Frozen.`);
422
+ return res.json({ status: "skipped_frozen" });
423
+ }
424
+ if (lastThrustDate === todayDate) {
425
+ console.log(`Skipping briefing: Thrust already exists for today.`);
426
+ return res.json({ status: "skipped_exists" });
427
+ }
428
 
429
+ // 2. Generate Briefing
430
+ const prompt = "It is 6 AM. Generate the Morning Briefing (New Thrust). If the project has been idle, use <freeze_project>true</freeze_project> after this.";
431
+
432
+ // Use Process endpoint logic internally
433
+ // We create a fake "request" to process
434
+ // Ideally refactor logic out, but for now calling AI directly:
435
+ const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
436
  const history = await StateManager.getHistory(projectId);
437
+
438
+ const aiResult = await callAI(history, prompt, {}, prompts.director_system_prompt, `[PRD]: ${lead.requirements_doc}`, SMART_MODEL_ID);
439
+
440
+ // 3. Save & Execute
441
+ await StateManager.addHistory(projectId, 'model', aiResult.text);
442
+ const cmds = extractCommands(aiResult.text);
443
+ await executeCommands(lead.user_id, projectId, cmds);
444
+
445
+ // 4. Force Freeze (Morning briefings lock the project until user returns)
446
+ // This ensures we don't pile up briefings on an abandoned project.
447
+ await StateManager.setFrozen(projectId, true);
448
+
449
+ res.json({ success: true });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450
 
451
  } catch (e) {
452
+ console.error("Morning Briefing Error", e);
453
+ res.status(500).json({ error: e.message });
454
  }
455
  });
456
 
457
+ app.listen(PORT, () => console.log(`✅ Core Online: ${PORT} | Smart: ${SMART_MODEL_ID} | Fast: ${FAST_MODEL_ID}`));