-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1378 lines (1157 loc) · 40.6 KB
/
server.js
File metadata and controls
1378 lines (1157 loc) · 40.6 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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Abacus Server
* A lightweight dashboard for visualizing and monitoring beads across multiple projects
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const chokidar = require('chokidar');
const Database = require('better-sqlite3');
// ============================================
// CLI Argument Parsing
// ============================================
/**
* Display help message and exit
*/
function showHelp() {
console.log(`
Usage: node server.js [options]
Options:
-p, --port <number> Port to run the server on (default: 5847)
-h, --help Show this help message
Environment:
PORT Port to run the server on (overridden by CLI flag)
Examples:
node server.js # Runs on port 5847
node server.js --port 8080 # Runs on port 8080
node server.js -p 4000 # Runs on port 4000
PORT=5000 node server.js # Runs on port 5000
PORT=5000 node server.js -p 8080 # Runs on port 8080 (CLI takes precedence)
`);
process.exit(0);
}
/**
* Validate port number
* @param {string|number} port - Port to validate
* @returns {number} - Valid port number
* @throws {Error} - If port is invalid
*/
function validatePort(port) {
const portNum = parseInt(port, 10);
if (isNaN(portNum)) {
console.error(`Error: Invalid port "${port}" - must be a number`);
process.exit(1);
}
if (portNum < 1 || portNum > 65535) {
console.error(`Error: Port ${portNum} out of range - must be between 1 and 65535`);
process.exit(1);
}
if (portNum < 1024) {
console.warn(`Warning: Port ${portNum} is a privileged port (< 1024) and may require elevated permissions`);
}
return portNum;
}
/**
* Parse command-line arguments
* @returns {Object} - Parsed arguments { port: number|undefined }
*/
function parseArgs() {
const args = process.argv.slice(2);
const result = { port: undefined };
for (let i = 0; i < args.length; i++) {
const arg = args[i];
// Help flag
if (arg === '-h' || arg === '--help') {
showHelp();
}
// Port flag: --port=<num>
if (arg.startsWith('--port=')) {
result.port = validatePort(arg.slice(7));
continue;
}
// Port flag: --port <num> or -p <num>
if (arg === '--port' || arg === '-p') {
const nextArg = args[i + 1];
if (!nextArg || nextArg.startsWith('-')) {
console.error(`Error: ${arg} requires a port number`);
process.exit(1);
}
result.port = validatePort(nextArg);
i++; // Skip next argument
continue;
}
// Unknown flag
if (arg.startsWith('-')) {
console.error(`Error: Unknown option "${arg}"`);
console.error('Use --help for usage information');
process.exit(1);
}
}
return result;
}
// Parse CLI arguments
const cliArgs = parseArgs();
// Configuration (precedence: CLI > ENV > default)
const PORT = cliArgs.port || (process.env.PORT ? validatePort(process.env.PORT) : 5847);
const CONFIG_DIR = path.join(process.env.HOME || process.env.USERPROFILE, '.abacus');
const PROJECTS_FILE = path.join(CONFIG_DIR, 'projects.json');
// Ensure config directory exists
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
// ============================================
// JSON File-based Database
// ============================================
/**
* Simple JSON file database for projects
*/
class ProjectsDB {
constructor(filePath) {
this.filePath = filePath;
this.data = { projects: [], nextId: 1 };
this.load();
}
load() {
try {
if (fs.existsSync(this.filePath)) {
const content = fs.readFileSync(this.filePath, 'utf-8');
this.data = JSON.parse(content);
}
} catch (error) {
console.error('Error loading projects file:', error);
this.data = { projects: [], nextId: 1 };
}
}
save() {
try {
fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
} catch (error) {
console.error('Error saving projects file:', error);
}
}
getAll() {
// Reload from file to pick up external changes (e.g., test resets)
this.load();
return this.data.projects.sort((a, b) => a.name.localeCompare(b.name));
}
getById(id) {
return this.data.projects.find(p => p.id === parseInt(id));
}
getByPath(projectPath) {
return this.data.projects.find(p => p.path === projectPath);
}
add(name, projectPath) {
const project = {
id: this.data.nextId++,
name,
path: projectPath,
created_at: new Date().toISOString()
};
this.data.projects.push(project);
this.save();
return project;
}
remove(id) {
const index = this.data.projects.findIndex(p => p.id === parseInt(id));
if (index !== -1) {
this.data.projects.splice(index, 1);
this.save();
return true;
}
return false;
}
}
// Initialize database
const db = new ProjectsDB(PROJECTS_FILE);
// File watchers for each project (issues.jsonl watchers)
const watchers = new Map();
// Database watchers for each project (beads.db watchers)
const dbWatchers = new Map();
// Debounce timers for db changes
const dbDebounceTimers = new Map();
// Cache of last broadcast data hash per project (to avoid duplicate broadcasts)
const lastBroadcastHash = new Map();
// SSE clients for real-time updates
const sseClients = new Set();
/**
* MIME types for serving static files
*/
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2'
};
/**
* Read beads from SQLite database
* @param {string} projectPath - Path to the project directory
* @returns {Array} - Array of bead objects
*/
function readBeadsFromSQLite(projectPath) {
const dbPath = path.join(projectPath, '.beads', 'beads.db');
if (!fs.existsSync(dbPath)) {
return [];
}
let db;
try {
db = new Database(dbPath, { readonly: true });
// Query issues (exclude deleted/tombstone)
const issues = db.prepare(`
SELECT
id, title, description, status, priority,
issue_type as type, assignee, created_at, updated_at
FROM issues
WHERE status != 'tombstone'
AND (deleted_at IS NULL OR deleted_at = '')
ORDER BY priority ASC, created_at DESC
`).all();
// Query dependencies for each issue
const getDeps = db.prepare(`
SELECT depends_on_id as target, type
FROM dependencies
WHERE issue_id = ?
`);
// Query labels for each issue
const getLabels = db.prepare(`
SELECT label FROM labels WHERE issue_id = ?
`);
// Enrich issues with dependencies and labels
return issues.map(issue => {
const dependencies = getDeps.all(issue.id);
const labels = getLabels.all(issue.id).map(l => l.label);
return {
...issue,
dependencies: dependencies.length > 0 ? dependencies : undefined,
labels: labels.length > 0 ? labels : undefined
};
});
} catch (error) {
console.error('Error reading beads from SQLite:', error);
return [];
} finally {
if (db) {
try { db.close(); } catch (e) { /* ignore close errors */ }
}
}
}
/**
* Read and parse issues.jsonl file from a project path
* @param {string} projectPath - Path to the project directory
* @returns {Array} - Array of bead objects
*/
function readBeadsFromJSONL(projectPath) {
const beadsPath = path.join(projectPath, '.beads', 'issues.jsonl');
if (!fs.existsSync(beadsPath)) {
return [];
}
try {
const content = fs.readFileSync(beadsPath, 'utf-8');
const lines = content.trim().split('\n').filter(line => line.trim());
return lines.map(line => {
try {
const bead = JSON.parse(line);
// Normalize dependencies to match SQLite format
// JSONL has { depends_on_id, type }, SQLite uses { target, type }
if (bead.dependencies && Array.isArray(bead.dependencies)) {
bead.dependencies = bead.dependencies.map(dep => ({
target: dep.depends_on_id || dep.target,
type: dep.type
}));
}
return bead;
} catch (e) {
console.error('Error parsing bead line:', e);
return null;
}
}).filter(bead => bead !== null);
} catch (error) {
console.error('Error reading beads file:', error);
return [];
}
}
/**
* Get the most recent updated_at timestamp from a list of beads
* @param {Array} beads - Array of bead objects
* @returns {Date|null} - Most recent timestamp or null
*/
function getNewestTimestamp(beads) {
if (!beads || beads.length === 0) return null;
let newest = null;
for (const bead of beads) {
if (bead.updated_at) {
const ts = new Date(bead.updated_at);
if (!newest || ts > newest) {
newest = ts;
}
}
}
return newest;
}
/**
* Read beads from a project
* Compares timestamps from both sources and uses whichever has newer data
* This handles both SQLite mode and no-db mode (JSONL-only)
* @param {string} projectPath - Path to the project directory
* @returns {Array} - Array of bead objects
*/
function readBeads(projectPath) {
const jsonlBeads = readBeadsFromJSONL(projectPath);
const sqliteBeads = readBeadsFromSQLite(projectPath);
// If only one source has data, use it
if (jsonlBeads.length === 0 && sqliteBeads.length === 0) {
return [];
}
if (jsonlBeads.length > 0 && sqliteBeads.length === 0) {
return jsonlBeads;
}
if (sqliteBeads.length > 0 && jsonlBeads.length === 0) {
return sqliteBeads;
}
// Both have data - compare timestamps to find newest
const jsonlNewest = getNewestTimestamp(jsonlBeads);
const sqliteNewest = getNewestTimestamp(sqliteBeads);
// If we can't determine timestamps, prefer SQLite (more likely to be current)
if (!jsonlNewest && !sqliteNewest) {
return sqliteBeads;
}
if (!jsonlNewest) {
return sqliteBeads;
}
if (!sqliteNewest) {
return jsonlBeads;
}
// Use whichever source has the most recently updated bead
if (sqliteNewest >= jsonlNewest) {
return sqliteBeads;
} else {
return jsonlBeads;
}
}
/**
* Validate that a path contains a valid beads project
* Accepts projects with either issues.jsonl OR beads.db (SQLite)
* @param {string} projectPath - Path to validate
* @returns {boolean} - True if valid beads project
*/
function isValidBeadsProject(projectPath) {
const beadsDir = path.join(projectPath, '.beads');
if (!fs.existsSync(beadsDir)) {
return false;
}
const beadsFile = path.join(beadsDir, 'issues.jsonl');
const beadsDb = path.join(beadsDir, 'beads.db');
// Valid if has JSONL file OR SQLite database
return fs.existsSync(beadsFile) || fs.existsSync(beadsDb);
}
/**
* Set up file watcher for a project
* @param {string} projectPath - Path to the project
*/
function watchProject(projectPath) {
if (watchers.has(projectPath)) {
return; // Already watching
}
const beadsDir = path.join(projectPath, '.beads');
const beadsPath = path.join(beadsDir, 'issues.jsonl');
const dbPath = path.join(beadsDir, 'beads.db');
if (fs.existsSync(beadsPath)) {
// Watch the JSONL file for changes
const watcher = chokidar.watch(beadsPath, {
persistent: true,
ignoreInitial: true
});
watcher.on('change', () => {
// Notify all SSE clients about the change
const beads = readBeads(projectPath);
const projectName = path.basename(projectPath);
sseClients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'update', project: projectPath, name: projectName, beads })}\n\n`);
});
});
watchers.set(projectPath, watcher);
console.log(`Watching JSONL: ${beadsPath}`);
}
// Also watch the SQLite database for changes
// When the database changes, read directly from SQLite and broadcast
// Watch all SQLite files: .db, .db-wal, .db-shm (SQLite writes to WAL first)
if (fs.existsSync(dbPath)) {
const dbFiles = [
dbPath,
`${dbPath}-wal`,
`${dbPath}-shm`
].filter(f => fs.existsSync(f));
const dbWatcher = chokidar.watch(dbFiles, {
persistent: true,
ignoreInitial: true,
// Use polling for SQLite files as they may not trigger normal fs events
usePolling: true,
interval: 500 // Check every 500ms for faster response
});
dbWatcher.on('change', (changedPath) => {
// Debounce rapid changes
const existingTimer = dbDebounceTimers.get(projectPath);
if (existingTimer) {
clearTimeout(existingTimer);
}
const timer = setTimeout(() => {
dbDebounceTimers.delete(projectPath);
// Read directly from SQLite and broadcast to clients
const beads = readBeadsFromSQLite(projectPath);
const projectName = path.basename(projectPath);
if (beads.length > 0) {
// Create a hash of the data to detect actual changes
const dataHash = JSON.stringify(beads.map(b => `${b.id}:${b.updated_at}`).sort());
const lastHash = lastBroadcastHash.get(projectPath);
// Only broadcast if data actually changed
if (dataHash !== lastHash) {
lastBroadcastHash.set(projectPath, dataHash);
sseClients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'update', project: projectPath, name: projectName, beads })}\n\n`);
});
console.log(`Broadcast ${beads.length} beads from SQLite for: ${projectPath}`);
}
}
}, 300); // 300ms debounce for faster response
dbDebounceTimers.set(projectPath, timer);
});
dbWatchers.set(projectPath, dbWatcher);
console.log(`Watching DB files: ${dbFiles.join(', ')}`);
}
}
/**
* Stop watching a project
* @param {string} projectPath - Path to stop watching
*/
function unwatchProject(projectPath) {
// Stop JSONL watcher
const watcher = watchers.get(projectPath);
if (watcher) {
watcher.close();
watchers.delete(projectPath);
console.log(`Stopped watching JSONL: ${projectPath}`);
}
// Stop DB watcher
const dbWatcher = dbWatchers.get(projectPath);
if (dbWatcher) {
dbWatcher.close();
dbWatchers.delete(projectPath);
console.log(`Stopped watching DB: ${projectPath}`);
}
// Clear any pending debounce timers
const timer = dbDebounceTimers.get(projectPath);
if (timer) {
clearTimeout(timer);
dbDebounceTimers.delete(projectPath);
}
}
/**
* Broadcast project update to all SSE clients
* @param {string} projectPath - Path to the project
*/
function broadcastProjectUpdate(projectPath) {
const beads = readBeads(projectPath);
const projectName = path.basename(projectPath);
// Update hash to prevent duplicate broadcasts from file watcher
const dataHash = JSON.stringify(beads.map(b => `${b.id}:${b.updated_at}`).sort());
lastBroadcastHash.set(projectPath, dataHash);
sseClients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'update', project: projectPath, name: projectName, beads })}\n\n`);
});
}
/**
* Add a label to a bead in SQLite database
* @param {string} projectPath - Path to the project
* @param {string} beadId - ID of the bead
* @param {string} label - Label to add
* @returns {Object} - Result with labels array or error
*/
function addLabelToBeadSQLite(projectPath, beadId, label) {
const dbPath = path.join(projectPath, '.beads', 'beads.db');
if (!fs.existsSync(dbPath)) {
return { error: 'SQLite database not found', status: 404 };
}
let database;
try {
database = new Database(dbPath);
// Check if bead exists
const bead = database.prepare('SELECT id FROM issues WHERE id = ?').get(beadId);
if (!bead) {
return { error: 'Bead not found', status: 404 };
}
// Insert label (ON CONFLICT DO NOTHING handles duplicates)
database.prepare('INSERT INTO labels (issue_id, label) VALUES (?, ?) ON CONFLICT DO NOTHING').run(beadId, label);
// Get all labels for the bead
const labels = database.prepare('SELECT label FROM labels WHERE issue_id = ?').all(beadId).map(l => l.label);
return { labels };
} catch (error) {
console.error('Error adding label to SQLite:', error);
// Provide more specific error messages
if (error.code === 'SQLITE_BUSY') {
return { error: 'Database is locked. Please try again.', status: 503 };
}
if (error.code === 'SQLITE_READONLY') {
return { error: 'Database is read-only', status: 403 };
}
return { error: `Database error: ${error.message}`, status: 500 };
} finally {
if (database) {
try { database.close(); } catch (e) { /* ignore close errors */ }
}
}
}
/**
* Remove a label from a bead in SQLite database
* @param {string} projectPath - Path to the project
* @param {string} beadId - ID of the bead
* @param {string} label - Label to remove
* @returns {Object} - Result with labels array or error
*/
function removeLabelFromBeadSQLite(projectPath, beadId, label) {
const dbPath = path.join(projectPath, '.beads', 'beads.db');
if (!fs.existsSync(dbPath)) {
return { error: 'SQLite database not found', status: 404 };
}
let database;
try {
database = new Database(dbPath);
// Check if bead exists
const bead = database.prepare('SELECT id FROM issues WHERE id = ?').get(beadId);
if (!bead) {
return { error: 'Bead not found', status: 404 };
}
// Check if label exists on bead
const existingLabel = database.prepare('SELECT label FROM labels WHERE issue_id = ? AND label = ?').get(beadId, label);
if (!existingLabel) {
return { error: 'Label not found on bead', status: 404 };
}
// Remove the label
database.prepare('DELETE FROM labels WHERE issue_id = ? AND label = ?').run(beadId, label);
// Get remaining labels for the bead
const labels = database.prepare('SELECT label FROM labels WHERE issue_id = ?').all(beadId).map(l => l.label);
return { labels };
} catch (error) {
console.error('Error removing label from SQLite:', error);
// Provide more specific error messages
if (error.code === 'SQLITE_BUSY') {
return { error: 'Database is locked. Please try again.', status: 503 };
}
if (error.code === 'SQLITE_READONLY') {
return { error: 'Database is read-only', status: 403 };
}
return { error: `Database error: ${error.message}`, status: 500 };
} finally {
if (database) {
try { database.close(); } catch (e) { /* ignore close errors */ }
}
}
}
/**
* Get comments for a bead from SQLite database
* @param {string} projectPath - Path to the project
* @param {string} beadId - ID of the bead
* @returns {Object} - Result with comments array or error
*/
function getCommentsForBead(projectPath, beadId) {
const dbPath = path.join(projectPath, '.beads', 'beads.db');
if (!fs.existsSync(dbPath)) {
// No SQLite database - check if bead exists in JSONL
const beads = readBeadsFromJSONL(projectPath);
const bead = beads.find(b => b.id === beadId);
if (!bead) {
return { error: 'Bead not found', status: 404 };
}
// JSONL doesn't have comments - return empty array
return { comments: [] };
}
let database;
try {
database = new Database(dbPath, { readonly: true });
// Check if bead exists
const bead = database.prepare('SELECT id FROM issues WHERE id = ?').get(beadId);
if (!bead) {
return { error: 'Bead not found', status: 404 };
}
// Check if comments table exists
const tableExists = database.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='comments'"
).get();
if (!tableExists) {
// No comments table - return empty array
return { comments: [] };
}
// Fetch comments ordered by created_at ASC
const comments = database.prepare(`
SELECT author, text as content, created_at
FROM comments
WHERE issue_id = ?
ORDER BY created_at ASC
`).all(beadId);
return { comments };
} catch (error) {
console.error('Error getting comments from SQLite:', error);
return { error: 'Database error', status: 500 };
} finally {
if (database) {
try { database.close(); } catch (e) { /* ignore close errors */ }
}
}
}
/**
* Get dependency chain for a bead (3-level BFS traversal)
* @param {string} projectPath - Path to the project
* @param {string} beadId - ID of the bead
* @param {number} maxDepth - Maximum traversal depth (default 3)
* @returns {Object} - Dependency chain with ancestors, descendants, cycle detection
*/
function getDependencyChain(projectPath, beadId, maxDepth = 3) {
const beads = readBeads(projectPath);
const beadMap = new Map(beads.map(b => [b.id, b]));
const bead = beadMap.get(beadId);
if (!bead) {
return null;
}
const visited = new Set([beadId]);
let hasCycle = false;
// Build map: beadId -> beads that BLOCK this bead (for finding ancestors)
// If bead A has "blocks" dependency on B, then A blocks B, meaning A is an ancestor of B
const blockedByMap = new Map();
for (const b of beads) {
const blocks = (b.dependencies || []).filter(d => d.type === 'blocks');
for (const dep of blocks) {
if (!blockedByMap.has(dep.target)) {
blockedByMap.set(dep.target, []);
}
blockedByMap.get(dep.target).push(b.id);
}
}
// Traverse ancestors (beads that block this bead)
const ancestors = [];
let ancestorsTruncated = false;
const ancestorQueue = [{ id: beadId, depth: 0, parentId: null }];
while (ancestorQueue.length > 0) {
const { id, depth, parentId } = ancestorQueue.shift();
if (depth > 0) {
const b = beadMap.get(id);
if (b) {
ancestors.push({
id: b.id,
title: b.title,
status: b.status,
priority: b.priority,
depth,
parentId
});
}
}
if (depth >= maxDepth) {
// Check if there are more blockers beyond this depth
const blockers = blockedByMap.get(id) || [];
if (blockers.length > 0) {
ancestorsTruncated = true;
}
continue;
}
// Find beads that block this one (ancestors)
const blockers = blockedByMap.get(id) || [];
for (const blockerId of blockers) {
if (visited.has(blockerId)) {
hasCycle = true;
continue;
}
visited.add(blockerId);
ancestorQueue.push({ id: blockerId, depth: depth + 1, parentId: id });
}
}
// Reset visited for descendant traversal (keep root bead)
visited.clear();
visited.add(beadId);
// Traverse descendants (beads that THIS bead blocks)
// Look at the bead's "blocks" dependencies directly
const descendants = [];
let descendantsTruncated = false;
const descendantQueue = [{ id: beadId, depth: 0, parentId: null }];
while (descendantQueue.length > 0) {
const { id, depth, parentId } = descendantQueue.shift();
if (depth > 0) {
const b = beadMap.get(id);
if (b) {
descendants.push({
id: b.id,
title: b.title,
status: b.status,
priority: b.priority,
depth,
parentId
});
}
}
if (depth >= maxDepth) {
// Check if there are more descendants beyond this depth
const current = beadMap.get(id);
const blocks = (current?.dependencies || []).filter(d => d.type === 'blocks');
if (blocks.length > 0) {
descendantsTruncated = true;
}
continue;
}
// Find beads that this one blocks (descendants)
const current = beadMap.get(id);
const blocks = (current?.dependencies || []).filter(d => d.type === 'blocks');
for (const dep of blocks) {
if (visited.has(dep.target)) {
hasCycle = true;
continue;
}
visited.add(dep.target);
descendantQueue.push({ id: dep.target, depth: depth + 1, parentId: id });
}
}
return {
bead: {
id: bead.id,
title: bead.title,
status: bead.status,
priority: bead.priority
},
ancestors,
descendants,
hasCycle,
truncated: {
ancestors: ancestorsTruncated,
descendants: descendantsTruncated
}
};
}
/**
* Parse JSON body from request
* @param {http.IncomingMessage} req - HTTP request
* @returns {Promise<Object>} - Parsed JSON body
*/
function parseJsonBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch (error) {
reject(error);
}
});
req.on('error', reject);
});
}
/**
* Send JSON response
* @param {http.ServerResponse} res - HTTP response
* @param {number} statusCode - HTTP status code
* @param {Object} data - Data to send as JSON
*/
function sendJson(res, statusCode, data) {
res.writeHead(statusCode, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
/**
* Serve static files
* @param {http.ServerResponse} res - HTTP response
* @param {string} filePath - Path to the file
*/
function serveStaticFile(res, filePath) {
const ext = path.extname(filePath);
const mimeType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('Not Found');
} else {
res.writeHead(500);
res.end('Server Error');
}
return;
}
res.writeHead(200, { 'Content-Type': mimeType });
res.end(data);
});
}
/**
* API Routes Handler
*/
const apiRoutes = {
// GET /api/browse - Browse filesystem directories
'GET /api/browse': (req, pathParts, query) => {
const requestedPath = query.path || (process.env.HOME || process.env.USERPROFILE || '/');
const resolvedPath = path.resolve(requestedPath);
// Security: basic path validation
if (!fs.existsSync(resolvedPath)) {
return { error: 'Path does not exist', status: 404 };
}
const stats = fs.statSync(resolvedPath);
if (!stats.isDirectory()) {
return { error: 'Path is not a directory', status: 400 };
}
try {
const entries = fs.readdirSync(resolvedPath, { withFileTypes: true });
const directories = [];
for (const entry of entries) {
// Skip hidden files/folders (starting with .) except .beads
if (entry.name.startsWith('.') && entry.name !== '.beads') {
continue;
}
if (entry.isDirectory()) {
const fullPath = path.join(resolvedPath, entry.name);
const hasBeads = fs.existsSync(path.join(fullPath, '.beads'));
directories.push({
name: entry.name,
path: fullPath,
hasBeads
});
}
}
// Sort: folders with .beads first, then alphabetically
directories.sort((a, b) => {
if (a.hasBeads && !b.hasBeads) return -1;
if (!a.hasBeads && b.hasBeads) return 1;
return a.name.localeCompare(b.name);
});
// Get parent directory (unless at root)
const parentPath = path.dirname(resolvedPath);
const hasParent = parentPath !== resolvedPath;
return {
current: resolvedPath,
parent: hasParent ? parentPath : null,
directories,
isBeadsProject: fs.existsSync(path.join(resolvedPath, '.beads'))
};
} catch (error) {
console.error('Browse error:', error);
return { error: 'Cannot read directory', status: 403 };
}
},
// GET /api/projects - List all projects
'GET /api/projects': () => {
const projects = db.getAll();
return projects.map(project => ({
...project,
beadCount: readBeads(project.path).length
}));
},
// POST /api/projects - Add a new project
'POST /api/projects': async (req) => {
const body = await parseJsonBody(req);
const { path: projectPath } = body;
if (!projectPath) {
return { error: 'Project path is required', status: 400 };
}
// Resolve and normalize the path
const resolvedPath = path.resolve(projectPath);
// Check if path exists
if (!fs.existsSync(resolvedPath)) {
return { error: 'Path does not exist', status: 400 };