-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathautensa-db.js
More file actions
586 lines (476 loc) · 17 KB
/
Copy pathautensa-db.js
File metadata and controls
586 lines (476 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
#!/usr/bin/env node
/**
* Autensa OpenCloser Mission Control - Database Edition
*
* Works with actual Mission Control SQLite database:
* /Users/nimbletenthousand/Desktop/apps/mission-control/mission-control.db
*/
const sqlite3 = require('sqlite3').verbose();
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const fs = require('fs').promises;
class AutensaMissionControlDB {
constructor() {
this.dbPath = path.join(process.env.HOME, 'Desktop', 'apps', 'mission-control', 'mission-control.db');
this.projectsBasePath = path.join(process.env.HOME, 'Documents', 'Shared', 'projects');
this.db = null;
}
async connect() {
return new Promise((resolve, reject) => {
this.db = new sqlite3.Database(this.dbPath, (err) => {
if (err) {
reject(new Error(`Failed to connect to database: ${err.message}`));
} else {
resolve();
}
});
});
}
async disconnect() {
return new Promise((resolve, reject) => {
if (this.db) {
this.db.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
resolve();
}
});
}
async query(sql, params = []) {
return new Promise((resolve, reject) => {
this.db.all(sql, params, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
}
async run(sql, params = []) {
return new Promise((resolve, reject) => {
this.db.run(sql, params, function(err) {
if (err) {
reject(err);
} else {
resolve({ lastID: this.lastID, changes: this.changes });
}
});
});
}
async getWorkspaces() {
return this.query(`
SELECT id, name, slug, description, icon,
datetime(created_at) as created_at,
datetime(updated_at) as updated_at
FROM workspaces
ORDER BY created_at DESC
`);
}
async getWorkspaceBySlug(slug) {
const rows = await this.query(
`SELECT * FROM workspaces WHERE slug = ?`,
[slug]
);
return rows[0] || null;
}
async getTasks(workspaceId = null) {
let sql = `
SELECT
t.id, t.title, t.description, t.status, t.priority,
t.workspace_id, t.due_date,
datetime(t.created_at) as created_at,
datetime(t.updated_at) as updated_at,
a.name as assigned_agent_name,
w.name as workspace_name
FROM tasks t
LEFT JOIN agents a ON t.assigned_agent_id = a.id
LEFT JOIN workspaces w ON t.workspace_id = w.id
`;
const params = [];
if (workspaceId) {
sql += ` WHERE t.workspace_id = ?`;
params.push(workspaceId);
}
sql += ` ORDER BY t.created_at DESC`;
return this.query(sql, params);
}
async getAgents() {
return this.query(`
SELECT id, name, role, created_at
FROM agents
ORDER BY name
`);
}
async createWorkspace(name, description = '', icon = '📁') {
const id = uuidv4();
const slug = this.createSlug(name);
await this.run(
`INSERT INTO workspaces (id, name, slug, description, icon)
VALUES (?, ?, ?, ?, ?)`,
[id, name, slug, description, icon]
);
// Create directory for markdown files
const workspacePath = path.join(this.projectsBasePath, slug);
await fs.mkdir(workspacePath, { recursive: true });
// Create project overview file
const overviewContent = `# ${name}
## Workspace Overview
**ID:** ${id}
**Slug:** ${slug}
**Created:** ${new Date().toLocaleDateString()}
**Description:** ${description}
## Database Information
This workspace is managed by Autensa Mission Control database.
- Workspace ID: ${id}
- Database: ${this.dbPath}
## Mission Control Integration
Tasks for this workspace are stored in the Mission Control database and can be accessed via:
- Mission Control dashboard: http://localhost:4000
- Database queries
- API endpoints (if configured)
## Generated Files
Markdown files in this directory are generated from database content for documentation purposes.
Created by Autensa OpenCloser Mission Control Skill`;
await fs.writeFile(
path.join(workspacePath, 'project-overview.md'),
overviewContent
);
return { id, name, slug, path: workspacePath };
}
async createTask(workspaceId, title, description = '', options = {}) {
const id = uuidv4();
const {
priority = 'normal',
status = 'planning',
assignedAgentId = null,
dueDate = null
} = options;
await this.run(
`INSERT INTO tasks (
id, title, description, workspace_id,
priority, status, assigned_agent_id, due_date
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[id, title, description, workspaceId, priority, status, assignedAgentId, dueDate]
);
// Generate markdown file for documentation
await this.generateTaskMarkdown(id, workspaceId);
return { id, title, workspaceId, status, priority };
}
async generateTaskMarkdown(taskId, workspaceId) {
const task = await this.getTaskById(taskId);
if (!task) return;
const workspace = await this.getWorkspaceById(workspaceId);
if (!workspace) return;
const workspacePath = path.join(this.projectsBasePath, workspace.slug);
await fs.mkdir(workspacePath, { recursive: true });
const taskSlug = this.createSlug(task.title);
const taskPath = path.join(workspacePath, `${taskSlug}.md`);
const taskContent = `# ${task.title}
## Task Information
**Task ID:** ${task.id}
**Workspace:** ${workspace.name}
**Status:** ${task.status}
**Priority:** ${task.priority}
**Created:** ${task.created_at}
**Last Updated:** ${task.updated_at}
## Description
${task.description || 'No description provided.'}
## Database Reference
- Task ID: ${task.id}
- Workspace ID: ${workspaceId}
- Assigned Agent: ${task.assigned_agent_name || 'Unassigned'}
- Due Date: ${task.due_date || 'No due date'}
## Mission Control Integration
This task is managed by Autensa Mission Control database.
All updates should be made through the Mission Control system.
## Notes
Generated by Autensa OpenCloser Mission Control Skill`;
await fs.writeFile(taskPath, taskContent);
return taskPath;
}
async getTaskById(taskId) {
const rows = await this.query(
`SELECT t.*, a.name as assigned_agent_name, w.name as workspace_name
FROM tasks t
LEFT JOIN agents a ON t.assigned_agent_id = a.id
LEFT JOIN workspaces w ON t.workspace_id = w.id
WHERE t.id = ?`,
[taskId]
);
return rows[0] || null;
}
async getWorkspaceById(workspaceId) {
const rows = await this.query(
`SELECT * FROM workspaces WHERE id = ?`,
[workspaceId]
);
return rows[0] || null;
}
async getWorkspaceTasks(workspaceId) {
return this.getTasks(workspaceId);
}
async assignTask(taskId, agentId) {
await this.run(
`UPDATE tasks SET assigned_agent_id = ?, updated_at = datetime('now') WHERE id = ?`,
[agentId, taskId]
);
// Update markdown file
const task = await this.getTaskById(taskId);
if (task) {
await this.generateTaskMarkdown(taskId, task.workspace_id);
}
return { taskId, agentId, updated: true };
}
async updateTaskStatus(taskId, status) {
await this.run(
`UPDATE tasks SET status = ?, updated_at = datetime('now') WHERE id = ?`,
[status, taskId]
);
// Update markdown file
const task = await this.getTaskById(taskId);
if (task) {
await this.generateTaskMarkdown(taskId, task.workspace_id);
}
return { taskId, status, updated: true };
}
createSlug(text) {
return text.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/--+/g, '-')
.trim();
}
async processCommand(command) {
await this.connect();
try {
const cmd = command.toLowerCase().trim();
if (cmd.includes('status') || cmd.includes('what') || cmd.includes('going')) {
return this.handleStatus(cmd);
}
if (cmd.includes('list') && cmd.includes('workspace')) {
return this.handleListWorkspaces();
}
if (cmd.includes('list') && cmd.includes('task')) {
return this.handleListTasks(cmd);
}
if (cmd.includes('list') && cmd.includes('agent')) {
return this.handleListAgents();
}
if (cmd.includes('create') && cmd.includes('workspace')) {
return this.handleCreateWorkspace(cmd);
}
if (cmd.includes('create') && cmd.includes('task')) {
return this.handleCreateTask(cmd);
}
if (cmd.includes('assign') && cmd.includes('task')) {
return this.handleAssignTask(cmd);
}
return this.respond(`Command not recognized: "${command}". Try: "list workspaces", "list tasks", "create workspace [name]", "create task [title]"`);
} finally {
await this.disconnect();
}
}
async handleStatus(cmd) {
const workspaces = await this.getWorkspaces();
const tasks = await this.getTasks();
const agents = await this.getAgents();
let response = `📊 Mission Control Status\n`;
response += `========================\n\n`;
response += `🏢 Workspaces: ${workspaces.length}\n`;
for (const ws of workspaces.slice(0, 3)) {
const wsTasks = await this.getWorkspaceTasks(ws.id);
response += ` • ${ws.name} (${wsTasks.length} tasks)\n`;
}
if (workspaces.length > 3) {
response += ` ... and ${workspaces.length - 3} more\n`;
}
response += `\n📋 Total Tasks: ${tasks.length}\n`;
const statusCounts = {};
tasks.forEach(t => {
statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
});
for (const [status, count] of Object.entries(statusCounts)) {
response += ` • ${status}: ${count}\n`;
}
response += `\n🤖 Agents: ${agents.length}\n`;
for (const agent of agents.slice(0, 3)) {
response += ` • ${agent.name} (${agent.role || 'No role'})\n`;
}
if (agents.length > 3) {
response += ` ... and ${agents.length - 3} more\n`;
}
response += `\n📍 Database: ${this.dbPath}\n`;
response += `📁 Files: ${this.projectsBasePath}\n`;
return this.respond(response);
}
async handleListWorkspaces() {
const workspaces = await this.getWorkspaces();
if (workspaces.length === 0) {
return this.respond('No workspaces found in Mission Control database.');
}
let response = `🏢 Mission Control Workspaces\n`;
response += `==============================\n\n`;
for (const ws of workspaces) {
const tasks = await this.getWorkspaceTasks(ws.id);
const filePath = path.join(this.projectsBasePath, ws.slug);
response += `📁 ${ws.name}\n`;
response += ` • ID: ${ws.id}\n`;
response += ` • Slug: ${ws.slug}\n`;
response += ` • Tasks: ${tasks.length}\n`;
response += ` • Created: ${ws.created_at}\n`;
response += ` • Files: ${filePath}\n\n`;
}
return this.respond(response);
}
async handleListTasks(cmd) {
// Try to extract workspace from command
let workspaceId = null;
if (cmd.includes('anniversary')) {
const workspace = await this.getWorkspaceBySlug('anniversary-gifts');
if (workspace) workspaceId = workspace.id;
}
const tasks = await this.getTasks(workspaceId);
if (tasks.length === 0) {
const msg = workspaceId
? 'No tasks found for specified workspace.'
: 'No tasks found in Mission Control database.';
return this.respond(msg);
}
let response = workspaceId
? `📋 Tasks in Workspace\n`
: `📋 All Mission Control Tasks\n`;
response += `=========================\n\n`;
for (const task of tasks.slice(0, 10)) {
response += `📄 ${task.title}\n`;
response += ` • ID: ${task.id}\n`;
response += ` • Status: ${task.status}\n`;
response += ` • Priority: ${task.priority}\n`;
response += ` • Workspace: ${task.workspace_name}\n`;
response += ` • Agent: ${task.assigned_agent_name || 'Unassigned'}\n`;
response += ` • Created: ${task.created_at}\n\n`;
}
if (tasks.length > 10) {
response += `... and ${tasks.length - 10} more tasks\n`;
}
return this.respond(response);
}
async handleListAgents() {
const agents = await this.getAgents();
if (agents.length === 0) {
return this.respond('No agents found in Mission Control database.');
}
let response = `🤖 Mission Control Agents\n`;
response += `=========================\n\n`;
for (const agent of agents) {
response += `👤 ${agent.name}\n`;
response += ` • ID: ${agent.id}\n`;
response += ` • Role: ${agent.role || 'No role specified'}\n`;
response += ` • Created: ${agent.created_at}\n\n`;
}
return this.respond(response);
}
async handleCreateWorkspace(cmd) {
// Extract workspace name from command
const match = cmd.match(/workspace\s+(.+)/) || cmd.match(/create\s+(.+)/);
if (!match) {
return this.respond('Please specify a workspace name. Example: "create workspace Anniversary Gifts"');
}
const name = match[1].replace(/workspace$/i, '').trim();
if (!name) {
return this.respond('Invalid workspace name.');
}
const result = await this.createWorkspace(name);
let response = `✅ Created workspace: ${result.name}\n`;
response += `📍 Workspace ID: ${result.id}\n`;
response += `📁 Slug: ${result.slug}\n`;
response += `🗂️ Files: ${result.path}\n\n`;
response += `Database entry created and markdown files generated.\n`;
response += `Access via Mission Control: http://localhost:4000\n`;
return this.respond(response);
}
async handleCreateTask(cmd) {
// This is a simplified version - in reality would need more parsing
// For now, create a task in the Anniversary Gifts workspace
const workspace = await this.getWorkspaceBySlug('anniversary-gifts');
if (!workspace) {
return this.respond('Anniversary Gifts workspace not found. Create it first with "create workspace Anniversary Gifts"');
}
// Extract task title from command
const match = cmd.match(/task\s+(.+)/) || cmd.match(/create\s+(.+)/);
if (!match) {
return this.respond('Please specify a task title. Example: "create task Mobile SEO Optimization"');
}
const title = match[1].replace(/task$/i, '').trim();
if (!title) {
return this.respond('Invalid task title.');
}
const result = await this.createTask(workspace.id, title);
let response = `✅ Created task: ${result.title}\n`;
response += `📍 Task ID: ${result.id}\n`;
response += `🏢 Workspace: ${workspace.name}\n`;
response += `📊 Status: ${result.status}\n`;
response += `🎯 Priority: ${result.priority}\n\n`;
response += `Task added to Mission Control database and markdown file generated.\n`;
return this.respond(response);
}
async handleAssignTask(cmd) {
// Simplified - would need task ID and agent ID parsing
return this.respond('Task assignment requires specific task ID and agent ID. Use Mission Control UI for complex assignments.');
}
respond(message) {
return {
success: true,
message: message,
timestamp: new Date().toISOString()
};
}
}
// CLI interface
if (require.main === module) {
const args = process.argv.slice(2);
const command = args.join(' ');
const skill = new AutensaMissionControlDB();
if (command) {
skill.processCommand(command)
.then(response => {
if (response.success) {
console.log(response.message);
} else {
console.error('Error:', response.message);
}
})
.catch(error => {
console.error('Unexpected error:', error.message);
console.error('\nTroubleshooting:');
console.error('1. Check if Mission Control is running');
console.error('2. Verify database exists:', skill.dbPath);
console.error('3. Ensure you have read/write permissions');
});
} else {
console.log(`Autensa OpenCloser Mission Control - Database Edition
Usage:
node autensa-db.js [command]
Commands:
status Show Mission Control status
list workspaces List all workspaces
list tasks List all tasks (or in specific workspace)
list agents List all agents
create workspace [name] Create new workspace
create task [title] Create task in Anniversary Gifts workspace
Examples:
node autensa-db.js "status"
node autensa-db.js "list workspaces"
node autensa-db.js "list tasks"
node autensa-db.js "create workspace New Project"
node autensa-db.js "create task Mobile SEO Optimization"
Database: ${new AutensaMissionControlDB().dbPath}
Files: ${new AutensaMissionControlDB().projectsBasePath}`);
}
}
module.exports = AutensaMissionControlDB;