everydaytok commited on
Commit
dcbe0f5
·
verified ·
1 Parent(s): f220346

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +52 -755
app.js CHANGED
@@ -4,9 +4,6 @@ import fs from 'fs';
4
  import path from 'path';
5
  import { createClient } from '@supabase/supabase-js';
6
 
7
- // ==========================================
8
- // 1. CONFIGURATION & SETUP
9
- // ==========================================
10
  const PORT = 7860;
11
  const SUPABASE_URL = process.env.SUPABASE_URL;
12
  const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
@@ -15,14 +12,10 @@ const FRONT_URL = process.env.FRONT_URL;
15
  const CRON_REGISTRY_URL = process.env.CRON_REGISTRY_URL || "http://localhost:7861";
16
  const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
17
 
18
- // --- MODEL CONFIGURATION ---
19
  const SMART_MODEL_ID = "claude";
20
  const FAST_MODEL_ID = "gpt-5-mini";
21
 
22
- if (!SUPABASE_URL || !SUPABASE_KEY) {
23
- console.error("FATAL: Missing Supabase URL or Service Key.");
24
- process.exit(1);
25
- }
26
 
27
  const app = express();
28
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
@@ -30,160 +23,67 @@ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
30
  app.use(express.json({ limit: '50mb' }));
31
  app.use(cors());
32
 
33
- // ==========================================
34
- // 2. PROMPT MANAGEMENT
35
- // ==========================================
36
  let prompts = {};
37
  try {
38
- const promptsPath = path.resolve('./prompts.json');
39
- if (fs.existsSync(promptsPath)) {
40
- prompts = JSON.parse(fs.readFileSync(promptsPath, 'utf8'));
41
- console.log("✅ Prompts loaded.");
42
- } else {
43
- throw new Error("prompts.json not found");
44
- }
45
- } catch (e) {
46
- console.error("❌ Prompt Load Error:", e.message);
47
- process.exit(1);
48
- }
49
 
50
- // ==========================================
51
- // 3. STATE MANAGER
52
- // ==========================================
53
  const activeProjects = new Map();
54
 
55
  const StateManager = {
56
  getHistory: async (projectId) => {
57
- if (activeProjects.has(projectId)) {
58
- const cached = activeProjects.get(projectId);
59
- cached.lastActive = Date.now();
60
- return cached.history;
61
- }
62
-
63
- const { data: chunks, error } = await supabase
64
- .from('message_chunks')
65
- .select('*')
66
- .eq('project_id', projectId)
67
- .order('chunk_index', { ascending: false })
68
- .limit(10);
69
-
70
- if (error) return [];
71
  const fullHistory = (chunks || []).reverse().flatMap(c => c.payload || []);
72
-
73
- activeProjects.set(projectId, { history: fullHistory, lastActive: Date.now(), isFrozen: false });
74
  return fullHistory;
75
  },
76
-
77
  addHistory: async (projectId, role, text) => {
78
  const newMessage = { role, parts: [{ text }] };
79
-
80
- if (activeProjects.has(projectId)) {
81
- const project = activeProjects.get(projectId);
82
- project.history.push(newMessage);
83
- project.lastActive = Date.now();
84
- if (role === 'user') project.isFrozen = false;
85
- }
86
-
87
  try {
88
- const { data: latestChunk } = await supabase
89
- .from('message_chunks')
90
- .select('id, chunk_index, payload')
91
- .eq('project_id', projectId)
92
- .order('chunk_index', { ascending: false })
93
- .limit(1)
94
- .single();
95
-
96
  const currentPayload = (latestChunk?.payload) || [];
97
-
98
  if (latestChunk && currentPayload.length < 20) {
99
- await supabase.from('message_chunks').update({
100
- payload: [...currentPayload, newMessage]
101
- }).eq('id', latestChunk.id);
102
  } else {
103
- await supabase.from('message_chunks').insert({
104
- project_id: projectId,
105
- lead_id: projectId,
106
- chunk_index: (latestChunk?.chunk_index ?? -1) + 1,
107
- payload: [newMessage]
108
- });
109
  }
110
-
111
- if (role === 'user') await supabase.from('leads').update({ is_frozen: false }).eq('id', projectId);
112
- } catch (e) { console.error("History Sync Error", e); }
113
  },
114
-
115
- isFrozen: async (projectId) => {
116
- if (activeProjects.has(projectId)) return activeProjects.get(projectId).isFrozen;
117
- const { data } = await supabase.from('leads').select('is_frozen').eq('id', projectId).single();
118
- return data?.is_frozen || false;
119
- },
120
-
121
  setFrozen: async (projectId, status) => {
122
  if (activeProjects.has(projectId)) activeProjects.get(projectId).isFrozen = status;
123
  await supabase.from('leads').update({ is_frozen: status }).eq('id', projectId);
124
  }
125
  };
126
 
127
- // ==========================================
128
- // 4. AI ENGINE
129
- // ==========================================
130
  const callAI = async (history, input, contextData, systemPrompt, projectContext, modelId) => {
131
  let contextStr = "";
132
  try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
133
-
134
- const recentHistory = history.slice(-10).map(m =>
135
- `${m.role === 'model' ? 'Assistant' : 'User'}: ${m.parts?.[0]?.text || ""}`
136
- ).join('\n');
137
-
138
  const fullPrompt = `System: ${systemPrompt}\n\n${projectContext}\n\n[HISTORY]:\n${recentHistory}\n\n[CONTEXT]: ${contextStr}\n\nUser: ${input}\nAssistant:`;
139
 
140
  try {
141
  const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
142
- method: 'POST',
143
- headers: { 'Content-Type': 'application/json' },
144
  body: JSON.stringify({ model: modelId, prompt: fullPrompt, system_prompt: systemPrompt })
145
  });
146
-
147
- if (!response.ok) throw new Error("AI API Error");
148
  const result = await response.json();
149
  return { text: result.data || result.text || "", usage: result.usage };
150
- } catch (e) {
151
- return { text: "<notification>AI Unreachable</notification>", usage: {} };
152
- }
153
  };
154
 
155
- // ==========================================
156
- // 5. COMMAND & CRON LOGIC
157
- // ==========================================
158
  function extractCommands(text) {
159
  const commands = [];
160
  const parse = (regex, type, isJson = true) => {
161
  let match;
162
  regex.lastIndex = 0;
163
- // Added 'gi' flags for case-insensitive and global multiline matching
164
  while ((match = regex.exec(text)) !== null) {
165
  let rawPayload = match[1].trim();
166
  try {
167
- if (isJson) {
168
- commands.push({ type, payload: JSON.parse(rawPayload) });
169
- } else {
170
- commands.push({ type, payload: rawPayload });
171
- }
172
  } catch (e) {
173
- console.error(`⚠️ Parse Error (${type}):`, e.message);
174
-
175
- // BULLETPROOF FALLBACK: If AI spits raw markdown instead of JSON, rescue it.
176
- if (type === 'create_thrust') {
177
- console.log(`[FALLBACK] Rescuing invalid JSON as raw markdown...`);
178
- commands.push({
179
- type,
180
- payload: {
181
- title: "System Thrust",
182
- markdown_content: rawPayload,
183
- tasks: []
184
- }
185
- });
186
- }
187
  }
188
  }
189
  };
@@ -195,6 +95,9 @@ function extractCommands(text) {
195
  parse(/<schedule_briefing>([\s\S]*?)<\/schedule_briefing>/gi, 'schedule_briefing');
196
  parse(/<freeze_project>([\s\S]*?)<\/freeze_project>/gi, 'freeze_project', false);
197
  parse(/<thrust_complete>([\s\S]*?)<\/thrust_complete>/gi, 'thrust_complete', false);
 
 
 
198
 
199
  return commands;
200
  }
@@ -202,46 +105,22 @@ function extractCommands(text) {
202
  async function registerMorningCron(projectId, offset) {
203
  const now = new Date();
204
  const target = new Date(now);
205
- const targetUtcHour = 6 - offset;
206
-
207
- target.setUTCHours(targetUtcHour, 0, 0, 0);
208
  if (target <= now) target.setDate(target.getDate() + 1);
209
-
210
  const delayMs = target.getTime() - now.getTime();
211
- const intervalMs = 24 * 60 * 60 * 1000;
212
-
213
- console.log(`⏰ Scheduling Briefing for ${projectId}. Next run in ${(delayMs/1000/60).toFixed(1)} mins.`);
214
-
215
- await fetch(`${CRON_REGISTRY_URL}/register`, {
216
- method: 'POST',
217
- headers: { 'Content-Type': 'application/json' },
218
- body: JSON.stringify({
219
- secret: CRON_SECRET,
220
- jobId: `briefing_${projectId}`,
221
- intervalMs: intervalMs,
222
- initialDelay: delayMs,
223
- webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`,
224
- leadId: projectId,
225
- payload: { projectId, timezoneOffset: offset }
226
- })
227
- }).catch(e => console.error("Cron Reg Error", e));
228
  }
229
 
230
  async function executeCommands(userId, projectId, commands) {
231
  let flags = { shouldReload: false, thrustComplete: false };
232
 
233
  for (const cmd of commands) {
234
- console.log(`[CMD] ${cmd.type} -> Project: ${projectId}`);
235
-
236
  try {
237
  if (cmd.type === 'create_thrust') {
238
- const { data: thrust } = await supabase.from('thrusts').insert({
239
- lead_id: projectId,
240
- title: cmd.payload.title,
241
- markdown_content: cmd.payload.markdown_content,
242
- status: 'active'
243
- }).select().single();
244
-
245
  if (thrust && cmd.payload.tasks && cmd.payload.tasks.length > 0) {
246
  const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
247
  await supabase.from('thrust_tasks').insert(tasks);
@@ -250,12 +129,7 @@ async function executeCommands(userId, projectId, commands) {
250
  }
251
 
252
  if (cmd.type === 'log_timeline') {
253
- await supabase.from('timeline_events').insert({
254
- lead_id: projectId,
255
- title: cmd.payload.title,
256
- description: cmd.payload.description,
257
- type: (cmd.payload.type || 'system').toLowerCase(),
258
- });
259
  flags.shouldReload = true;
260
  }
261
 
@@ -265,81 +139,57 @@ async function executeCommands(userId, projectId, commands) {
265
  }
266
 
267
  if (cmd.type === 'schedule_briefing') {
268
- const offset = cmd.payload.timezone_offset || 0;
269
- await registerMorningCron(projectId, offset);
270
  }
271
 
272
- if (cmd.type === 'freeze_project') {
273
- const isFrozen = cmd.payload === 'true';
274
- await StateManager.setFrozen(projectId, isFrozen);
275
- console.log(`❄️ Project ${projectId} Frozen: ${isFrozen}`);
 
 
 
276
  }
277
 
 
278
  if (cmd.type === 'thrust_complete') {
279
- flags.thrustComplete = true;
 
 
 
 
 
280
  }
281
 
282
  if (cmd.type === 'notification' && FRONT_URL) {
283
- fetch(`${FRONT_URL}/internal/notify`, {
284
- method: 'POST',
285
- headers: { 'Content-Type': 'application/json' },
286
- body: JSON.stringify({ user_id: userId, type: 'toast', message: cmd.payload })
287
- }).catch(() => {});
288
  }
289
 
290
- } catch (e) { console.error("Exec Error", e); }
291
  }
292
  return flags;
293
  }
294
 
295
- // ==========================================
296
- // 6. ENDPOINTS
297
- // ==========================================
298
-
299
- // --- INIT ---
300
  app.post('/init-project', async (req, res) => {
301
  const { userId, name, description, localPath } = req.body;
302
-
303
- const { data: lead, error } = await supabase.from('leads').insert({
304
- user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..."
305
- }).select().single();
306
-
307
- if (error || !lead) return res.status(500).json({ error: "Failed to create project" });
308
-
309
  res.json({ success: true, leadId: lead.id });
310
 
311
- // Run AI processing in background
312
  setImmediate(async () => {
313
  try {
314
  const initInput = `PROJECT: ${name}\nDESC: ${description}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
315
  const aiResult = await callAI([], initInput, {}, prompts.init_system_prompt, "", SMART_MODEL_ID);
316
-
317
- // Explicitly force a success notification command so the UI reacts
318
  aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
319
-
320
  await StateManager.addHistory(lead.id, 'user', initInput);
321
  await StateManager.addHistory(lead.id, 'model', aiResult.text);
322
-
323
  const cmds = extractCommands(aiResult.text);
324
  await executeCommands(userId, lead.id, cmds);
325
- } catch (err) {
326
- console.error("❌ Background Init Failed:", err);
327
- // Notify frontend of failure
328
- if (FRONT_URL) {
329
- fetch(`${FRONT_URL}/internal/notify`, {
330
- method: 'POST',
331
- headers: { 'Content-Type': 'application/json' },
332
- body: JSON.stringify({ user_id: userId, type: 'toast', message: "Initialization AI Error." })
333
- }).catch(() => {});
334
- }
335
- }
336
  });
337
  });
338
 
339
- // --- MAIN PROCESS ---
340
  app.post('/process', async (req, res) => {
341
  const { userId, projectId, prompt, context, task_type = 'chat' } = req.body;
342
-
343
  if (task_type === 'chat') await StateManager.setFrozen(projectId, false);
344
 
345
  let selectedModel = (task_type === 'log_ingestion') ? FAST_MODEL_ID : SMART_MODEL_ID;
@@ -347,502 +197,23 @@ app.post('/process', async (req, res) => {
347
 
348
  try {
349
  const { data: lead } = await supabase.from('leads').select('requirements_doc').eq('id', projectId).single();
350
- const { data: activeThrust } = await supabase.from('thrusts')
351
- .select('title, tasks:thrust_tasks(title, status)')
352
- .eq('lead_id', projectId)
353
- .eq('status', 'active')
354
- .order('created_at', { ascending: false })
355
- .limit(1)
356
- .single();
357
-
358
- const { data: timeline } = await supabase.from('timeline_events')
359
- .select('title, type, description, created_at')
360
- .eq('lead_id', projectId)
361
- .order('created_at', { ascending: false })
362
- .limit(10);
363
-
364
- const projectContext = `
365
- [PRD]: ${lead?.requirements_doc?.substring(0, 3000)}...
366
-
367
- [CURRENT THRUST]:
368
- ${activeThrust ? JSON.stringify(activeThrust, null, 2) : "None"}
369
-
370
- [RECENT TIMELINE]:
371
- ${JSON.stringify(timeline || [], null, 2)}
372
- `;
373
-
374
- const history = await StateManager.getHistory(projectId);
375
- if (task_type === 'chat') await StateManager.addHistory(projectId, 'user', prompt);
376
-
377
- let aiResult = await callAI(history, prompt, context, sysPrompt, projectContext, selectedModel);
378
- let cmds = extractCommands(aiResult.text);
379
- let flags = await executeCommands(userId, projectId, cmds);
380
-
381
- if (flags.thrustComplete && task_type === 'log_ingestion') {
382
- console.log(`🚀 Thrust Complete detected by Analyst. Escalating to Director...`);
383
-
384
- const escalationPrompt = "The previous thrust is complete based on logs. Generate the next Thrust immediately to keep momentum.";
385
- const smartResult = await callAI(history, escalationPrompt, context, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
386
-
387
- aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
388
-
389
- const smartCmds = extractCommands(smartResult.text);
390
- await executeCommands(userId, projectId, smartCmds);
391
-
392
- await StateManager.addHistory(projectId, 'model', aiResult.text);
393
- } else {
394
- await StateManager.addHistory(projectId, 'model', aiResult.text);
395
- }
396
-
397
- const cleanText = aiResult.text.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, '').trim();
398
- res.json({ text: cleanText, should_reload: flags.shouldReload });
399
-
400
- } catch (e) {
401
- console.error(e);
402
- res.status(500).json({ error: "Processing Error" });
403
- }
404
- });
405
-
406
- // --- AUTOMATED MORNING BRIEFING ---
407
- app.post('/automated-briefing', async (req, res) => {
408
- const { projectId } = req.body;
409
- console.log(`☀️ Morning Briefing Triggered: ${projectId}`);
410
-
411
- try {
412
- const isFrozen = await StateManager.isFrozen(projectId);
413
-
414
- const { data: lastThrust } = await supabase.from('thrusts')
415
- .select('created_at')
416
- .eq('lead_id', projectId)
417
- .order('created_at', { ascending: false })
418
- .limit(1)
419
- .single();
420
-
421
- const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
422
- const todayDate = new Date().getDate();
423
-
424
- if (isFrozen) return res.json({ status: "skipped_frozen" });
425
- if (lastThrustDate === todayDate) return res.json({ status: "skipped_exists" });
426
-
427
- 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.";
428
-
429
- const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
430
- const { data: timeline } = await supabase.from('timeline_events')
431
- .select('*').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(5);
432
 
433
- const projectContext = `[PRD]: ${lead.requirements_doc}\n[TIMELINE]: ${JSON.stringify(timeline)}`;
434
  const history = await StateManager.getHistory(projectId);
435
 
436
- const aiResult = await callAI(history, prompt, {}, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
437
-
438
- await StateManager.addHistory(projectId, 'model', aiResult.text);
439
- const cmds = extractCommands(aiResult.text);
440
- await executeCommands(lead.user_id, projectId, cmds);
441
-
442
- await StateManager.setFrozen(projectId, true);
443
-
444
- res.json({ success: true });
445
-
446
- } catch (e) {
447
- console.error("Morning Briefing Error", e);
448
- res.status(500).json({ error: e.message });
449
- }
450
- });
451
-
452
- app.get('/', async (req, res) => {
453
- res.status(200).json({ status: "Alive" });
454
- });
455
-
456
- app.listen(PORT, () => {
457
- console.log(`✅ Core Online: ${PORT} | Smart: ${SMART_MODEL_ID} | Fast: ${FAST_MODEL_ID}`);
458
- });
459
-
460
- /* import express from 'express';
461
- import cors from 'cors';
462
- import fs from 'fs';
463
- import path from 'path';
464
- import { createClient } from '@supabase/supabase-js';
465
-
466
-
467
- // ==========================================
468
- // 1. CONFIGURATION & SETUP
469
- // ==========================================
470
- const PORT = 7860;
471
- const SUPABASE_URL = process.env.SUPABASE_URL;
472
- const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
473
- const REMOTE_SERVER_URL = process.env.REMOTE_AI_URL || "http://localhost:11434"; // Defaulting to local if env missing
474
- const FRONT_URL = process.env.FRONT_URL;
475
- const CRON_REGISTRY_URL = process.env.CRON_REGISTRY_URL || "http://localhost:7861";
476
- const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
477
-
478
- // --- MODEL CONFIGURATION ---
479
- const SMART_MODEL_ID = "claude";
480
- const FAST_MODEL_ID = "gpt-5-mini";
481
-
482
- if (!SUPABASE_URL || !SUPABASE_KEY) {
483
- console.error("FATAL: Missing Supabase URL or Service Key.");
484
- process.exit(1);
485
- }
486
-
487
- const app = express();
488
- const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
489
-
490
- app.use(express.json({ limit: '50mb' }));
491
- app.use(cors());
492
-
493
- // ==========================================
494
- // 2. PROMPT MANAGEMENT
495
- // ==========================================
496
- let prompts = {};
497
- try {
498
- const promptsPath = path.resolve('./prompts.json');
499
- if (fs.existsSync(promptsPath)) {
500
- const fileData = fs.readFileSync(promptsPath, 'utf8');
501
- prompts = JSON.parse(fileData);
502
- console.log("✅ Prompts loaded.");
503
- } else {
504
- throw new Error("prompts.json not found");
505
- }
506
- } catch (e) {
507
- console.error("❌ Prompt Load Error:", e.message);
508
- process.exit(1);
509
- }
510
-
511
- // ==========================================
512
- // 3. STATE MANAGER
513
- // ==========================================
514
- const activeProjects = new Map();
515
-
516
- const StateManager = {
517
- getHistory: async (projectId) => {
518
- if (activeProjects.has(projectId)) {
519
- const cached = activeProjects.get(projectId);
520
- cached.lastActive = Date.now();
521
- return cached.history;
522
- }
523
-
524
- const { data: chunks, error } = await supabase
525
- .from('message_chunks')
526
- .select('*')
527
- .eq('project_id', projectId)
528
- .order('chunk_index', { ascending: false })
529
- .limit(10);
530
-
531
- if (error) return [];
532
- const fullHistory = (chunks || []).reverse().flatMap(c => c.payload || []);
533
-
534
- // Initialize Cache with default frozen state (false)
535
- activeProjects.set(projectId, { history: fullHistory, lastActive: Date.now(), isFrozen: false });
536
- return fullHistory;
537
- },
538
-
539
- addHistory: async (projectId, role, text) => {
540
- const newMessage = { role, parts: [{ text }] };
541
-
542
- // Cache update
543
- if (activeProjects.has(projectId)) {
544
- const project = activeProjects.get(projectId);
545
- project.history.push(newMessage);
546
- project.lastActive = Date.now();
547
- // User activity unfreezes project automatically
548
- if (role === 'user') project.isFrozen = false;
549
- }
550
-
551
- // DB Sync (Chunking Logic)
552
- try {
553
- const { data: latestChunk } = await supabase
554
- .from('message_chunks')
555
- .select('id, chunk_index, payload')
556
- .eq('project_id', projectId)
557
- .order('chunk_index', { ascending: false })
558
- .limit(1)
559
- .single();
560
-
561
- const currentPayload = (latestChunk?.payload) || [];
562
-
563
- if (latestChunk && currentPayload.length < 20) {
564
- await supabase.from('message_chunks').update({
565
- payload: [...currentPayload, newMessage]
566
- }).eq('id', latestChunk.id);
567
- } else {
568
- await supabase.from('message_chunks').insert({
569
- project_id: projectId,
570
- lead_id: projectId,
571
- chunk_index: (latestChunk?.chunk_index ?? -1) + 1,
572
- payload: [newMessage]
573
- });
574
- }
575
-
576
- // If user spoke, unfreeze in DB
577
- if (role === 'user') {
578
- await supabase.from('leads').update({ is_frozen: false }).eq('id', projectId);
579
- }
580
-
581
- } catch (e) { console.error("History Sync Error", e); }
582
- },
583
-
584
- isFrozen: async (projectId) => {
585
- if (activeProjects.has(projectId)) return activeProjects.get(projectId).isFrozen;
586
- const { data } = await supabase.from('leads').select('is_frozen').eq('id', projectId).single();
587
- return data?.is_frozen || false;
588
- },
589
-
590
- setFrozen: async (projectId, status) => {
591
- if (activeProjects.has(projectId)) activeProjects.get(projectId).isFrozen = status;
592
- await supabase.from('leads').update({ is_frozen: status }).eq('id', projectId);
593
- }
594
- };
595
-
596
- // ==========================================
597
- // 4. AI ENGINE
598
- // ==========================================
599
-
600
- const callAI = async (history, input, contextData, systemPrompt, projectContext, modelId) => {
601
- let contextStr = "";
602
- try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
603
-
604
- const recentHistory = history.slice(-10).map(m =>
605
- `${m.role === 'model' ? 'Assistant' : 'User'}: ${m.parts?.[0]?.text || ""}`
606
- ).join('\n');
607
-
608
- const fullPrompt = `System: ${systemPrompt}\n\n${projectContext}\n\n[HISTORY]:\n${recentHistory}\n\n[CONTEXT]: ${contextStr}\n\nUser: ${input}\nAssistant:`;
609
-
610
- try {
611
- const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
612
- method: 'POST',
613
- headers: { 'Content-Type': 'application/json' },
614
- body: JSON.stringify({ model: modelId, prompt: fullPrompt, system_prompt: systemPrompt })
615
- });
616
-
617
- if (!response.ok) throw new Error("AI API Error");
618
- const result = await response.json();
619
- return { text: result.data || result.text || "", usage: result.usage };
620
- } catch (e) {
621
- return { text: "<notification>AI Unreachable</notification>", usage: {} };
622
- }
623
- };
624
-
625
- // ==========================================
626
- // 5. COMMAND & CRON LOGIC
627
- // ==========================================
628
-
629
- function extractCommands(text) {
630
- const commands = [];
631
- const parse = (regex, type, isJson = true) => {
632
- let match;
633
- regex.lastIndex = 0;
634
- while ((match = regex.exec(text)) !== null) {
635
- try {
636
- commands.push({ type, payload: isJson ? JSON.parse(match[1]) : match[1].trim() });
637
- } catch (e) { console.error(`Parse Error (${type})`, e); }
638
- }
639
- };
640
-
641
- parse(/<thrust_create>([\s\S]*?)<\/thrust_create>/g, 'create_thrust');
642
- parse(/<timeline_log>([\s\S]*?)<\/timeline_log>/g, 'log_timeline');
643
- parse(/<notification>([\s\S]*?)<\/notification>/g, 'notification', false);
644
- parse(/<update_requirements>([\s\S]*?)<\/update_requirements>/g, 'update_requirements', false);
645
- parse(/<schedule_briefing>([\s\S]*?)<\/schedule_briefing>/g, 'schedule_briefing');
646
- parse(/<freeze_project>([\s\S]*?)<\/freeze_project>/g, 'freeze_project', false);
647
- parse(/<thrust_complete>([\s\S]*?)<\/thrust_complete>/g, 'thrust_complete', false);
648
-
649
- return commands;
650
- }
651
-
652
- // Logic: Calculate delay until 6AM user time, register Cron with that initial delay
653
- async function registerMorningCron(projectId, offset) {
654
- const now = new Date();
655
- const target = new Date(now);
656
-
657
- // Logic: 6 AM relative to user offset.
658
- // E.g., Offset -5 (EST). UTC is 11 AM when EST is 6 AM.
659
- // Target UTC hour = 6 - offset.
660
- const targetUtcHour = 6 - offset;
661
-
662
- target.setUTCHours(targetUtcHour, 0, 0, 0);
663
-
664
- if (target <= now) {
665
- target.setDate(target.getDate() + 1); // Move to tomorrow
666
- }
667
-
668
- const delayMs = target.getTime() - now.getTime();
669
- const intervalMs = 24 * 60 * 60 * 1000; // 24 Hours
670
-
671
- console.log(`⏰ Scheduling Briefing for ${projectId}. Next run in ${(delayMs/1000/60).toFixed(1)} mins.`);
672
-
673
- await fetch(`${CRON_REGISTRY_URL}/register`, {
674
- method: 'POST',
675
- headers: { 'Content-Type': 'application/json' },
676
- body: JSON.stringify({
677
- secret: CRON_SECRET,
678
- jobId: `briefing_${projectId}`,
679
- intervalMs: intervalMs,
680
- initialDelay: delayMs,
681
- webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`,
682
- // ADD THIS LINE BELOW:
683
- leadId: projectId, // <--- Passes the UUID to the Cron Registry
684
- payload: { projectId, timezoneOffset: offset }
685
- })
686
- }).catch(e => console.error("Cron Reg Error", e));
687
-
688
-
689
- }
690
-
691
- async function executeCommands(userId, projectId, commands) {
692
- let flags = { shouldReload: false, thrustComplete: false };
693
-
694
- for (const cmd of commands) {
695
- console.log(`[CMD] ${cmd.type} -> Project: ${projectId}`);
696
-
697
- try {
698
- if (cmd.type === 'create_thrust') {
699
- const { data: thrust } = await supabase.from('thrusts').insert({
700
- lead_id: projectId,
701
- title: cmd.payload.title,
702
- markdown_content: cmd.payload.markdown_content,
703
- status: 'active'
704
- }).select().single();
705
-
706
- if (thrust && cmd.payload.tasks) {
707
- const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
708
- await supabase.from('thrust_tasks').insert(tasks);
709
- }
710
- flags.shouldReload = true;
711
- }
712
-
713
- if (cmd.type === 'log_timeline') {
714
- await supabase.from('timeline_events').insert({
715
- lead_id: projectId,
716
- title: cmd.payload.title,
717
- description: cmd.payload.description,
718
- type: (cmd.payload.type || 'system').toLowerCase(),
719
- });
720
- flags.shouldReload = true;
721
- }
722
-
723
- if (cmd.type === 'update_requirements') {
724
- await supabase.from('leads').update({ requirements_doc: cmd.payload }).eq('id', projectId);
725
- flags.shouldReload = true;
726
- }
727
-
728
- if (cmd.type === 'schedule_briefing') {
729
- const offset = cmd.payload.timezone_offset || 0;
730
- await registerMorningCron(projectId, offset);
731
- }
732
-
733
- if (cmd.type === 'freeze_project') {
734
- const isFrozen = cmd.payload === 'true';
735
- await StateManager.setFrozen(projectId, isFrozen);
736
- console.log(`❄️ Project ${projectId} Frozen: ${isFrozen}`);
737
- }
738
-
739
- if (cmd.type === 'thrust_complete') {
740
- flags.thrustComplete = true; // Signal for escalation
741
- }
742
-
743
- if (cmd.type === 'notification' && FRONT_URL) {
744
- fetch(`${FRONT_URL}/internal/notify`, {
745
- method: 'POST',
746
- headers: { 'Content-Type': 'application/json' },
747
- body: JSON.stringify({ user_id: userId, type: 'toast', message: cmd.payload })
748
- }).catch(() => {});
749
- }
750
-
751
- } catch (e) { console.error("Exec Error", e); }
752
- }
753
- return flags;
754
- }
755
-
756
- // ==========================================
757
- // 6. ENDPOINTS
758
- // ==========================================
759
-
760
- // --- INIT ---
761
- app.post('/init-project', async (req, res) => {
762
- const { userId, name, description, localPath } = req.body;
763
-
764
- const { data: lead, error } = await supabase.from('leads').insert({
765
- user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..."
766
- }).select().single();
767
-
768
- console.log(lead);
769
- console.log(error);
770
-
771
- res.json({ success: true, leadId: lead.id });
772
-
773
- setImmediate(async () => {
774
- const initInput = `PROJECT: ${name}\nDESC: ${description}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
775
- const aiResult = await callAI([], initInput, {}, prompts.init_system_prompt, "", SMART_MODEL_ID);
776
-
777
- await StateManager.addHistory(lead.id, 'user', initInput);
778
- await StateManager.addHistory(lead.id, 'model', aiResult.text);
779
-
780
- const cmds = extractCommands(aiResult.text);
781
- await executeCommands(userId, lead.id, cmds);
782
- });
783
- });
784
-
785
- // --- MAIN PROCESS ---
786
- app.post('/process', async (req, res) => {
787
- const { userId, projectId, prompt, context, task_type = 'chat' } = req.body;
788
-
789
- // 1. Unfreeze if user interacts
790
- if (task_type === 'chat') await StateManager.setFrozen(projectId, false);
791
-
792
- // 2. Select Model (Log Ingestion = Fast, High Level = Smart)
793
- let selectedModel = (task_type === 'log_ingestion') ? FAST_MODEL_ID : SMART_MODEL_ID;
794
- let sysPrompt = (task_type === 'log_ingestion') ? prompts.log_analyst_prompt : prompts.director_system_prompt;
795
-
796
- try {
797
- // 3. Build Context (God View: PRD + Timeline + Active Thrust)
798
- const { data: lead } = await supabase.from('leads').select('requirements_doc').eq('id', projectId).single();
799
- const { data: activeThrust } = await supabase.from('thrusts')
800
- .select('title, tasks:thrust_tasks(title, status)')
801
- .eq('lead_id', projectId)
802
- .eq('status', 'active')
803
- .order('created_at', { ascending: false })
804
- .limit(1)
805
- .single();
806
-
807
- // FETCH TIMELINE (Restored functionality)
808
- const { data: timeline } = await supabase.from('timeline_events')
809
- .select('title, type, description, created_at')
810
- .eq('lead_id', projectId)
811
- .order('created_at', { ascending: false })
812
- .limit(10); // Look at last 10 events for context
813
-
814
- const projectContext = `
815
- [PRD]: ${lead?.requirements_doc?.substring(0, 3000)}...
816
-
817
- [CURRENT THRUST]:
818
- ${activeThrust ? JSON.stringify(activeThrust, null, 2) : "None"}
819
-
820
- [RECENT TIMELINE]:
821
- ${JSON.stringify(timeline || [], null, 2)}
822
- `;
823
-
824
- const history = await StateManager.getHistory(projectId);
825
- if (task_type === 'chat') await StateManager.addHistory(projectId, 'user', prompt);
826
-
827
- // 4. AI Execution
828
  let aiResult = await callAI(history, prompt, context, sysPrompt, projectContext, selectedModel);
829
  let cmds = extractCommands(aiResult.text);
830
  let flags = await executeCommands(userId, projectId, cmds);
831
 
832
- // 5. AUTO-ESCALATION (Fast -> Smart)
833
- // Logic: Analyst determines thrust is done via logs -> Triggers Director to set new Aim.
834
  if (flags.thrustComplete && task_type === 'log_ingestion') {
835
- console.log(`🚀 Thrust Complete detected by Analyst. Escalating to Director...`);
836
-
837
  const escalationPrompt = "The previous thrust is complete based on logs. Generate the next Thrust immediately to keep momentum.";
838
- // Call Smart Model
839
  const smartResult = await callAI(history, escalationPrompt, context, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
840
-
841
  aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
842
-
843
  const smartCmds = extractCommands(smartResult.text);
844
  await executeCommands(userId, projectId, smartCmds);
845
-
846
  await StateManager.addHistory(projectId, 'model', aiResult.text);
847
  } else {
848
  await StateManager.addHistory(projectId, 'model', aiResult.text);
@@ -850,82 +221,8 @@ app.post('/process', async (req, res) => {
850
 
851
  const cleanText = aiResult.text.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, '').trim();
852
  res.json({ text: cleanText, should_reload: flags.shouldReload });
853
-
854
- } catch (e) {
855
- console.error(e);
856
- res.status(500).json({ error: "Processing Error" });
857
- }
858
  });
859
 
860
- // --- AUTOMATED MORNING BRIEFING (Called by Cron) ---
861
- app.post('/automated-briefing', async (req, res) => {
862
- const { projectId } = req.body;
863
- console.log(`☀️ Morning Briefing Triggered: ${projectId}`);
864
-
865
- try {
866
- const isFrozen = await StateManager.isFrozen(projectId);
867
-
868
- const { data: lastThrust } = await supabase.from('thrusts')
869
- .select('created_at')
870
- .eq('lead_id', projectId)
871
- .order('created_at', { ascending: false })
872
- .limit(1)
873
- .single();
874
-
875
- const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
876
- const todayDate = new Date().getDate();
877
-
878
- // Prevent generating if project is dead (frozen) or if generated recently
879
- if (isFrozen) {
880
- console.log(`Skipping briefing: Project Frozen.`);
881
- return res.json({ status: "skipped_frozen" });
882
- }
883
- if (lastThrustDate === todayDate) {
884
- console.log(`Skipping briefing: Thrust already exists for today.`);
885
- return res.json({ status: "skipped_exists" });
886
- }
887
-
888
- // Generate Briefing
889
- 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.";
890
-
891
- // Manually build context context for the automated call
892
- const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
893
- const { data: timeline } = await supabase.from('timeline_events')
894
- .select('*').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(5);
895
-
896
- const projectContext = `[PRD]: ${lead.requirements_doc}\n[TIMELINE]: ${JSON.stringify(timeline)}`;
897
- const history = await StateManager.getHistory(projectId);
898
-
899
- const aiResult = await callAI(history, prompt, {}, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
900
-
901
- await StateManager.addHistory(projectId, 'model', aiResult.text);
902
- const cmds = extractCommands(aiResult.text);
903
- await executeCommands(lead.user_id, projectId, cmds);
904
-
905
- // Morning briefings set the project to Frozen state until user returns
906
- // This prevents the AI from generating 30 briefings for an abandoned project
907
- await StateManager.setFrozen(projectId, true);
908
-
909
- res.json({ success: true });
910
-
911
- } catch (e) {
912
- console.error("Morning Briefing Error", e);
913
- res.status(500).json({ error: e.message });
914
- }
915
- });
916
- app.get('/', async (req, res) => {
917
- res.status(200).json({ status: "Alive" });
918
- });
919
-
920
- app.listen(PORT, () => {
921
- console.log(`✅ Core Online: ${PORT} | Smart: ${SMART_MODEL_ID} | Fast: ${FAST_MODEL_ID}`);
922
-
923
- console.log(`SUPABASE_URL ${SUPABASE_URL}`);
924
- console.log(`SUPABASE_KEY ${SUPABASE_KEY}`);
925
- console.log(`REMOTE_SERVER_URL ${REMOTE_SERVER_URL}`);
926
- console.log(`FRONT_URL ${FRONT_URL}`);
927
- console.log(`CRON_REGISTRY_URL ${CRON_REGISTRY_URL}`);
928
- console.log(`CRON_SECRET ${CRON_SECRET}`);
929
-
930
- });
931
- */
 
4
  import path from 'path';
5
  import { createClient } from '@supabase/supabase-js';
6
 
 
 
 
7
  const PORT = 7860;
8
  const SUPABASE_URL = process.env.SUPABASE_URL;
9
  const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
 
12
  const CRON_REGISTRY_URL = process.env.CRON_REGISTRY_URL || "http://localhost:7861";
13
  const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
14
 
 
15
  const SMART_MODEL_ID = "claude";
16
  const FAST_MODEL_ID = "gpt-5-mini";
17
 
18
+ if (!SUPABASE_URL || !SUPABASE_KEY) process.exit(1);
 
 
 
19
 
20
  const app = express();
21
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
 
23
  app.use(express.json({ limit: '50mb' }));
24
  app.use(cors());
25
 
 
 
 
26
  let prompts = {};
27
  try {
28
+ prompts = JSON.parse(fs.readFileSync(path.resolve('./prompts.json'), 'utf8'));
29
+ } catch (e) { process.exit(1); }
 
 
 
 
 
 
 
 
 
30
 
 
 
 
31
  const activeProjects = new Map();
32
 
33
  const StateManager = {
34
  getHistory: async (projectId) => {
35
+ if (activeProjects.has(projectId)) return activeProjects.get(projectId).history;
36
+ const { data: chunks } = await supabase.from('message_chunks').select('*').eq('project_id', projectId).order('chunk_index', { ascending: false }).limit(10);
 
 
 
 
 
 
 
 
 
 
 
 
37
  const fullHistory = (chunks || []).reverse().flatMap(c => c.payload || []);
38
+ activeProjects.set(projectId, { history: fullHistory, isFrozen: false });
 
39
  return fullHistory;
40
  },
 
41
  addHistory: async (projectId, role, text) => {
42
  const newMessage = { role, parts: [{ text }] };
43
+ if (activeProjects.has(projectId)) activeProjects.get(projectId).history.push(newMessage);
 
 
 
 
 
 
 
44
  try {
45
+ const { data: latestChunk } = await supabase.from('message_chunks').select('id, chunk_index, payload').eq('project_id', projectId).order('chunk_index', { ascending: false }).limit(1).single();
 
 
 
 
 
 
 
46
  const currentPayload = (latestChunk?.payload) || [];
 
47
  if (latestChunk && currentPayload.length < 20) {
48
+ await supabase.from('message_chunks').update({ payload: [...currentPayload, newMessage] }).eq('id', latestChunk.id);
 
 
49
  } else {
50
+ await supabase.from('message_chunks').insert({ project_id: projectId, lead_id: projectId, chunk_index: (latestChunk?.chunk_index ?? -1) + 1, payload: [newMessage] });
 
 
 
 
 
51
  }
52
+ } catch (e) {}
 
 
53
  },
 
 
 
 
 
 
 
54
  setFrozen: async (projectId, status) => {
55
  if (activeProjects.has(projectId)) activeProjects.get(projectId).isFrozen = status;
56
  await supabase.from('leads').update({ is_frozen: status }).eq('id', projectId);
57
  }
58
  };
59
 
 
 
 
60
  const callAI = async (history, input, contextData, systemPrompt, projectContext, modelId) => {
61
  let contextStr = "";
62
  try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
63
+ const recentHistory = history.slice(-10).map(m => `${m.role === 'model' ? 'Assistant' : 'User'}: ${m.parts?.[0]?.text || ""}`).join('\n');
 
 
 
 
64
  const fullPrompt = `System: ${systemPrompt}\n\n${projectContext}\n\n[HISTORY]:\n${recentHistory}\n\n[CONTEXT]: ${contextStr}\n\nUser: ${input}\nAssistant:`;
65
 
66
  try {
67
  const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
68
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
 
69
  body: JSON.stringify({ model: modelId, prompt: fullPrompt, system_prompt: systemPrompt })
70
  });
 
 
71
  const result = await response.json();
72
  return { text: result.data || result.text || "", usage: result.usage };
73
+ } catch (e) { return { text: "<notification>AI Unreachable</notification>", usage: {} }; }
 
 
74
  };
75
 
 
 
 
76
  function extractCommands(text) {
77
  const commands = [];
78
  const parse = (regex, type, isJson = true) => {
79
  let match;
80
  regex.lastIndex = 0;
 
81
  while ((match = regex.exec(text)) !== null) {
82
  let rawPayload = match[1].trim();
83
  try {
84
+ commands.push({ type, payload: isJson ? JSON.parse(rawPayload) : rawPayload });
 
 
 
 
85
  } catch (e) {
86
+ if (type === 'create_thrust') commands.push({ type, payload: { title: "System Thrust", markdown_content: rawPayload, tasks: [] } });
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  }
88
  }
89
  };
 
95
  parse(/<schedule_briefing>([\s\S]*?)<\/schedule_briefing>/gi, 'schedule_briefing');
96
  parse(/<freeze_project>([\s\S]*?)<\/freeze_project>/gi, 'freeze_project', false);
97
  parse(/<thrust_complete>([\s\S]*?)<\/thrust_complete>/gi, 'thrust_complete', false);
98
+
99
+ // NEW: Parse AI checking off tasks
100
+ parse(/<complete_task>([\s\S]*?)<\/complete_task>/gi, 'complete_task', false);
101
 
102
  return commands;
103
  }
 
105
  async function registerMorningCron(projectId, offset) {
106
  const now = new Date();
107
  const target = new Date(now);
108
+ target.setUTCHours(6 - offset, 0, 0, 0);
 
 
109
  if (target <= now) target.setDate(target.getDate() + 1);
 
110
  const delayMs = target.getTime() - now.getTime();
111
+ fetch(`${CRON_REGISTRY_URL}/register`, {
112
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
113
+ body: JSON.stringify({ secret: CRON_SECRET, jobId: `briefing_${projectId}`, intervalMs: 86400000, initialDelay: delayMs, webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`, leadId: projectId, payload: { projectId, timezoneOffset: offset } })
114
+ }).catch(()=>{});
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  }
116
 
117
  async function executeCommands(userId, projectId, commands) {
118
  let flags = { shouldReload: false, thrustComplete: false };
119
 
120
  for (const cmd of commands) {
 
 
121
  try {
122
  if (cmd.type === 'create_thrust') {
123
+ const { data: thrust } = await supabase.from('thrusts').insert({ lead_id: projectId, title: cmd.payload.title, markdown_content: cmd.payload.markdown_content, status: 'active' }).select().single();
 
 
 
 
 
 
124
  if (thrust && cmd.payload.tasks && cmd.payload.tasks.length > 0) {
125
  const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
126
  await supabase.from('thrust_tasks').insert(tasks);
 
129
  }
130
 
131
  if (cmd.type === 'log_timeline') {
132
+ await supabase.from('timeline_events').insert({ lead_id: projectId, title: cmd.payload.title, description: cmd.payload.description, type: (cmd.payload.type || 'system').toLowerCase() });
 
 
 
 
 
133
  flags.shouldReload = true;
134
  }
135
 
 
139
  }
140
 
141
  if (cmd.type === 'schedule_briefing') {
142
+ await registerMorningCron(projectId, cmd.payload.timezone_offset || 0);
 
143
  }
144
 
145
+ // NEW: AI checks off a specific task
146
+ if (cmd.type === 'complete_task') {
147
+ const { data: active } = await supabase.from('thrusts').select('id').eq('lead_id', projectId).eq('status', 'active').single();
148
+ if (active) {
149
+ await supabase.from('thrust_tasks').update({ status: 'done' }).eq('thrust_id', active.id).ilike('title', `%${cmd.payload}%`);
150
+ flags.shouldReload = true;
151
+ }
152
  }
153
 
154
+ // NEW: AI marks thrust as complete, we delete all its tasks
155
  if (cmd.type === 'thrust_complete') {
156
+ const { data: active } = await supabase.from('thrusts').select('id').eq('lead_id', projectId).eq('status', 'active').single();
157
+ if (active) {
158
+ await supabase.from('thrusts').update({ status: 'completed' }).eq('id', active.id);
159
+ await supabase.from('thrust_tasks').delete().eq('thrust_id', active.id);
160
+ flags.thrustComplete = true;
161
+ }
162
  }
163
 
164
  if (cmd.type === 'notification' && FRONT_URL) {
165
+ fetch(`${FRONT_URL}/internal/notify`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userId, type: 'toast', message: cmd.payload }) }).catch(() => {});
 
 
 
 
166
  }
167
 
168
+ } catch (e) {}
169
  }
170
  return flags;
171
  }
172
 
 
 
 
 
 
173
  app.post('/init-project', async (req, res) => {
174
  const { userId, name, description, localPath } = req.body;
175
+ const { data: lead } = await supabase.from('leads').insert({ user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..." }).select().single();
 
 
 
 
 
 
176
  res.json({ success: true, leadId: lead.id });
177
 
 
178
  setImmediate(async () => {
179
  try {
180
  const initInput = `PROJECT: ${name}\nDESC: ${description}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
181
  const aiResult = await callAI([], initInput, {}, prompts.init_system_prompt, "", SMART_MODEL_ID);
 
 
182
  aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
 
183
  await StateManager.addHistory(lead.id, 'user', initInput);
184
  await StateManager.addHistory(lead.id, 'model', aiResult.text);
 
185
  const cmds = extractCommands(aiResult.text);
186
  await executeCommands(userId, lead.id, cmds);
187
+ } catch (err) {}
 
 
 
 
 
 
 
 
 
 
188
  });
189
  });
190
 
 
191
  app.post('/process', async (req, res) => {
192
  const { userId, projectId, prompt, context, task_type = 'chat' } = req.body;
 
193
  if (task_type === 'chat') await StateManager.setFrozen(projectId, false);
194
 
195
  let selectedModel = (task_type === 'log_ingestion') ? FAST_MODEL_ID : SMART_MODEL_ID;
 
197
 
198
  try {
199
  const { data: lead } = await supabase.from('leads').select('requirements_doc').eq('id', projectId).single();
200
+ const { data: activeThrust } = await supabase.from('thrusts').select('title, tasks:thrust_tasks(title, status)').eq('lead_id', projectId).eq('status', 'active').order('created_at', { ascending: false }).limit(1).single();
201
+ const { data: timeline } = await supabase.from('timeline_events').select('title, type, description, created_at').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(10);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
+ const projectContext = `[PRD]: ${lead?.requirements_doc?.substring(0, 3000)}...\n[CURRENT THRUST]: ${activeThrust ? JSON.stringify(activeThrust) : "None"}\n[RECENT TIMELINE]: ${JSON.stringify(timeline || [])}`;
204
  const history = await StateManager.getHistory(projectId);
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  let aiResult = await callAI(history, prompt, context, sysPrompt, projectContext, selectedModel);
207
  let cmds = extractCommands(aiResult.text);
208
  let flags = await executeCommands(userId, projectId, cmds);
209
 
210
+ // Escalation: If fast model marks thrust complete, ask smart model for next thrust immediately
 
211
  if (flags.thrustComplete && task_type === 'log_ingestion') {
 
 
212
  const escalationPrompt = "The previous thrust is complete based on logs. Generate the next Thrust immediately to keep momentum.";
 
213
  const smartResult = await callAI(history, escalationPrompt, context, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
 
214
  aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
 
215
  const smartCmds = extractCommands(smartResult.text);
216
  await executeCommands(userId, projectId, smartCmds);
 
217
  await StateManager.addHistory(projectId, 'model', aiResult.text);
218
  } else {
219
  await StateManager.addHistory(projectId, 'model', aiResult.text);
 
221
 
222
  const cleanText = aiResult.text.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, '').trim();
223
  res.json({ text: cleanText, should_reload: flags.shouldReload });
224
+ } catch (e) { res.status(500).json({ error: "Processing Error" }); }
 
 
 
 
225
  });
226
 
227
+ app.get('/', async (req, res) => res.status(200).json({ status: "Alive" }));
228
+ app.listen(PORT, () => console.log(`✅ Core Online: ${PORT}`));