-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
4106 lines (3653 loc) · 142 KB
/
server.js
File metadata and controls
4106 lines (3653 loc) · 142 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
import express from 'express';
import Database from 'better-sqlite3';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import { execFileSync } from 'child_process';
const app = express();
const db = new Database('mission_control.db');
const PORT = 3001;
const DEFAULT_SCAN_ROOTS = ['C:/Users/lweis/Documents'];
const PROJECT_MARKERS = ['.git', 'package.json', 'pyproject.toml', 'requirements.txt', '.gsd'];
const ARTIFACT_RULES = [
{ relativePath: '.gsd/PROJECT.md', artifactType: 'gsd_project' },
{ relativePath: '.gsd/REQUIREMENTS.md', artifactType: 'gsd_requirements' },
{ relativePath: '.gsd/DECISIONS.md', artifactType: 'gsd_decisions' },
{ relativePath: 'ROADMAP.md', artifactType: 'roadmap_md' },
{ relativePath: 'MILESTONES.md', artifactType: 'milestones_md' },
{ relativePath: 'README.md', artifactType: 'readme' },
{ relativePath: 'PROJECT.md', artifactType: 'generic_plan' },
{ relativePath: 'PLAN.md', artifactType: 'generic_plan' },
{ relativePath: 'TODO.md', artifactType: 'generic_todo' },
{ relativePath: 'init_todos.json', artifactType: 'generic_todo' },
];
const DOCS_ROADMAP_DIR = path.join('docs', 'roadmap');
app.use(cors());
app.use(express.json());
db.pragma('journal_mode = WAL');
function tableExists(tableName) {
const row = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(tableName);
return Boolean(row);
}
function getColumnNames(tableName) {
return db.prepare(`PRAGMA table_info(${tableName})`).all().map((column) => column.name);
}
function migrateLegacyProjectsTable() {
if (!tableExists('projects')) return;
if (tableExists('projects_legacy')) return;
const projectColumns = getColumnNames('projects');
const isLegacyProjectsTable = projectColumns.includes('status') && projectColumns.includes('version') && !projectColumns.includes('root_path');
if (isLegacyProjectsTable) {
db.exec('ALTER TABLE projects RENAME TO projects_legacy');
}
}
migrateLegacyProjectsTable();
db.exec(`
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
slug TEXT NOT NULL,
root_path TEXT NOT NULL UNIQUE,
repo_type TEXT NOT NULL,
project_type TEXT NOT NULL,
primary_language TEXT,
framework TEXT,
package_manager TEXT,
has_git INTEGER NOT NULL DEFAULT 0,
planning_status TEXT NOT NULL DEFAULT 'none',
last_scanned_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS source_artifacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
artifact_type TEXT NOT NULL,
path TEXT NOT NULL,
title TEXT,
confidence REAL NOT NULL DEFAULT 1.0,
last_seen_at TEXT NOT NULL,
parse_status TEXT NOT NULL DEFAULT 'detected',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(project_id, path),
FOREIGN KEY(project_id) REFERENCES projects(id)
);
CREATE TABLE IF NOT EXISTS scan_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
root_path TEXT NOT NULL,
status TEXT NOT NULL,
projects_found INTEGER NOT NULL DEFAULT 0,
artifacts_found INTEGER NOT NULL DEFAULT 0,
summary TEXT,
started_at TEXT NOT NULL,
completed_at TEXT
);
CREATE TABLE IF NOT EXISTS import_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
status TEXT NOT NULL,
strategy TEXT NOT NULL,
started_at TEXT NOT NULL,
completed_at TEXT,
summary TEXT,
warnings_json TEXT,
FOREIGN KEY(project_id) REFERENCES projects(id)
);
CREATE TABLE IF NOT EXISTS milestones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
external_key TEXT,
title TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL DEFAULT 'draft',
origin TEXT NOT NULL DEFAULT 'imported',
confidence REAL NOT NULL DEFAULT 1.0,
needs_review INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
source_artifact_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id),
FOREIGN KEY(source_artifact_id) REFERENCES source_artifacts(id)
);
CREATE TABLE IF NOT EXISTS slices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
milestone_id INTEGER NOT NULL,
external_key TEXT,
title TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL DEFAULT 'draft',
origin TEXT NOT NULL DEFAULT 'imported',
confidence REAL NOT NULL DEFAULT 1.0,
needs_review INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
source_artifact_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id),
FOREIGN KEY(milestone_id) REFERENCES milestones(id),
FOREIGN KEY(source_artifact_id) REFERENCES source_artifacts(id)
);
CREATE TABLE IF NOT EXISTS planning_tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
milestone_id INTEGER,
slice_id INTEGER,
external_key TEXT,
title TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL DEFAULT 'draft',
category TEXT,
priority TEXT,
origin TEXT NOT NULL DEFAULT 'imported',
confidence REAL NOT NULL DEFAULT 1.0,
needs_review INTEGER NOT NULL DEFAULT 0,
source_artifact_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id),
FOREIGN KEY(milestone_id) REFERENCES milestones(id),
FOREIGN KEY(slice_id) REFERENCES slices(id),
FOREIGN KEY(source_artifact_id) REFERENCES source_artifacts(id)
);
CREATE TABLE IF NOT EXISTS requirements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
external_key TEXT,
title TEXT NOT NULL,
description TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
validation TEXT,
notes TEXT,
primary_owner TEXT,
supporting_slices TEXT,
source_artifact_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id),
FOREIGN KEY(source_artifact_id) REFERENCES source_artifacts(id)
);
CREATE TABLE IF NOT EXISTS decisions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
external_key TEXT,
scope TEXT,
decision TEXT NOT NULL,
choice TEXT,
rationale TEXT,
revisable TEXT,
when_context TEXT,
source_artifact_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(project_id) REFERENCES projects(id),
FOREIGN KEY(source_artifact_id) REFERENCES source_artifacts(id)
);
CREATE TABLE IF NOT EXISTS evidence_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
entity_type TEXT NOT NULL,
entity_id INTEGER NOT NULL,
source_artifact_id INTEGER NOT NULL,
excerpt TEXT,
line_start INTEGER,
line_end INTEGER,
confidence REAL NOT NULL DEFAULT 1.0,
reason TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY(source_artifact_id) REFERENCES source_artifacts(id)
);
CREATE TABLE IF NOT EXISTS projects_legacy (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE,
status TEXT,
version TEXT
);
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER,
title TEXT,
category TEXT,
status TEXT,
FOREIGN KEY(project_id) REFERENCES projects_legacy(id)
);
CREATE TABLE IF NOT EXISTS bootstrap_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL REFERENCES projects(id),
component_id TEXT NOT NULL,
action TEXT NOT NULL,
stage TEXT NOT NULL,
path TEXT,
template_id TEXT,
applied_at TEXT NOT NULL,
source_gap TEXT
);
CREATE INDEX IF NOT EXISTS idx_bootstrap_actions_project_id ON bootstrap_actions(project_id);
CREATE INDEX IF NOT EXISTS idx_projects_root_path ON projects(root_path);
CREATE INDEX IF NOT EXISTS idx_artifacts_project_id ON source_artifacts(project_id);
CREATE INDEX IF NOT EXISTS idx_scan_runs_started_at ON scan_runs(started_at DESC);
CREATE INDEX IF NOT EXISTS idx_import_runs_project_id ON import_runs(project_id);
CREATE INDEX IF NOT EXISTS idx_milestones_project_id ON milestones(project_id);
CREATE INDEX IF NOT EXISTS idx_slices_project_id ON slices(project_id);
CREATE INDEX IF NOT EXISTS idx_slices_milestone_id ON slices(milestone_id);
CREATE INDEX IF NOT EXISTS idx_planning_tasks_project_id ON planning_tasks(project_id);
CREATE INDEX IF NOT EXISTS idx_planning_tasks_slice_id ON planning_tasks(slice_id);
CREATE INDEX IF NOT EXISTS idx_requirements_project_id ON requirements(project_id);
CREATE INDEX IF NOT EXISTS idx_decisions_project_id ON decisions(project_id);
CREATE INDEX IF NOT EXISTS idx_evidence_links_entity ON evidence_links(entity_type, entity_id);
CREATE TABLE IF NOT EXISTS scan_paths (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL UNIQUE,
enabled INTEGER NOT NULL DEFAULT 1,
recursive INTEGER NOT NULL DEFAULT 1,
max_depth INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_scan_paths_enabled ON scan_paths(enabled);
`);
// ── Additive schema migrations (idempotent) ──────────────────────────────────
// proof_level on milestones: 'claimed' (status=done in ROADMAP) vs 'proven' (SUMMARY parsed + passed)
try { db.exec(`ALTER TABLE milestones ADD COLUMN proof_level TEXT NOT NULL DEFAULT 'claimed'`); } catch (_) { /* column already exists */ }
// ── Initialize default scan paths if table is empty ──────────────────────────
const scanPathCount = db.prepare('SELECT COUNT(*) as count FROM scan_paths').get();
if (scanPathCount.count === 0) {
const now = new Date().toISOString();
const insertDefaultPath = db.prepare(`
INSERT INTO scan_paths (path, enabled, recursive, max_depth, created_at, updated_at)
VALUES (?, 1, 1, NULL, ?, ?)
`);
DEFAULT_SCAN_ROOTS.forEach(root => {
try {
insertDefaultPath.run(root, now, now);
} catch (_) { /* path might already exist */ }
});
}
// source_artifact_id on proof evidence_links — already present on evidence_links, no migration needed
const getLegacyProjectByName = db.prepare('SELECT id FROM projects_legacy WHERE name = ?');
const getLegacyTasksByProjectId = db.prepare('SELECT * FROM tasks WHERE project_id = ? ORDER BY id ASC');
const getProjectByRootPath = db.prepare('SELECT id FROM projects WHERE root_path = ?');
const insertProject = db.prepare(`
INSERT INTO projects (
name, slug, root_path, repo_type, project_type, primary_language, framework, package_manager,
has_git, planning_status, last_scanned_at, created_at, updated_at
) VALUES (
@name, @slug, @root_path, @repo_type, @project_type, @primary_language, @framework, @package_manager,
@has_git, @planning_status, @last_scanned_at, @created_at, @updated_at
)
`);
const updateProject = db.prepare(`
UPDATE projects
SET name = @name,
slug = @slug,
repo_type = @repo_type,
project_type = @project_type,
primary_language = @primary_language,
framework = @framework,
package_manager = @package_manager,
has_git = @has_git,
planning_status = @planning_status,
last_scanned_at = @last_scanned_at,
updated_at = @updated_at
WHERE root_path = @root_path
`);
const upsertArtifact = db.prepare(`
INSERT INTO source_artifacts (
project_id, artifact_type, path, title, confidence, last_seen_at, parse_status, created_at, updated_at
) VALUES (
@project_id, @artifact_type, @path, @title, @confidence, @last_seen_at, @parse_status, @created_at, @updated_at
)
ON CONFLICT(project_id, path) DO UPDATE SET
artifact_type = excluded.artifact_type,
title = excluded.title,
confidence = excluded.confidence,
last_seen_at = excluded.last_seen_at,
parse_status = excluded.parse_status,
updated_at = excluded.updated_at
`);
const insertScanRun = db.prepare(`
INSERT INTO scan_runs (root_path, status, projects_found, artifacts_found, summary, started_at, completed_at)
VALUES (@root_path, @status, @projects_found, @artifacts_found, @summary, @started_at, @completed_at)
`);
const updateScanRun = db.prepare(`
UPDATE scan_runs
SET status = @status,
projects_found = @projects_found,
artifacts_found = @artifacts_found,
summary = @summary,
completed_at = @completed_at
WHERE id = @id
`);
const listProjects = db.prepare(`
SELECT p.*, COUNT(sa.id) AS artifact_count
FROM projects p
LEFT JOIN source_artifacts sa ON sa.project_id = p.id
GROUP BY p.id
ORDER BY LOWER(p.name) ASC
`);
const listArtifactsByProjectId = db.prepare(`
SELECT id, project_id, artifact_type, path, title, confidence, parse_status, last_seen_at, created_at, updated_at
FROM source_artifacts
WHERE project_id = ?
ORDER BY path ASC
`);
const listRecentScanRuns = db.prepare(`
SELECT *
FROM scan_runs
ORDER BY started_at DESC, id DESC
LIMIT ?
`);
const getProjectById = db.prepare(`
SELECT p.*, COUNT(sa.id) AS artifact_count
FROM projects p
LEFT JOIN source_artifacts sa ON sa.project_id = p.id
WHERE p.id = ?
GROUP BY p.id
`);
const listMilestonesByProjectId = db.prepare(`
SELECT *
FROM milestones
WHERE project_id = ?
ORDER BY sort_order ASC, id ASC
`);
const listSlicesByProjectId = db.prepare(`
SELECT *
FROM slices
WHERE project_id = ?
ORDER BY sort_order ASC, id ASC
`);
const listPlanningTasksByProjectId = db.prepare(`
SELECT *
FROM planning_tasks
WHERE project_id = ?
ORDER BY id ASC
`);
const listRequirementsByProjectId = db.prepare(`
SELECT *
FROM requirements
WHERE project_id = ?
ORDER BY external_key ASC, id ASC
`);
const listDecisionsByProjectId = db.prepare(`
SELECT *
FROM decisions
WHERE project_id = ?
ORDER BY id ASC
`);
const listImportRunsByProjectId = db.prepare(`
SELECT *
FROM import_runs
WHERE project_id = ?
ORDER BY started_at DESC, id DESC
`);
const getGsdProjectArtifactByProjectId = db.prepare(`
SELECT *
FROM source_artifacts
WHERE project_id = ? AND artifact_type = 'gsd_project'
ORDER BY id ASC
LIMIT 1
`);
const insertImportRun = db.prepare(`
INSERT INTO import_runs (
project_id, status, strategy, started_at, completed_at, summary, warnings_json
) VALUES (
@project_id, @status, @strategy, @started_at, @completed_at, @summary, @warnings_json
)
`);
const updateImportRun = db.prepare(`
UPDATE import_runs
SET status = @status,
completed_at = @completed_at,
summary = @summary,
warnings_json = @warnings_json
WHERE id = @id
`);
const getMilestoneByProjectArtifactAndKey = db.prepare(`
SELECT *
FROM milestones
WHERE project_id = @project_id
AND source_artifact_id = @source_artifact_id
AND external_key = @external_key
LIMIT 1
`);
const getMilestoneByProjectAndKey = db.prepare(`
SELECT *
FROM milestones
WHERE project_id = @project_id
AND external_key = @external_key
LIMIT 1
`);
const insertMilestone = db.prepare(`
INSERT INTO milestones (
project_id, external_key, title, description, status, origin, confidence,
needs_review, sort_order, source_artifact_id, created_at, updated_at
) VALUES (
@project_id, @external_key, @title, @description, @status, @origin, @confidence,
@needs_review, @sort_order, @source_artifact_id, @created_at, @updated_at
)
`);
const updateMilestone = db.prepare(`
UPDATE milestones
SET title = @title,
description = @description,
status = @status,
origin = @origin,
confidence = @confidence,
needs_review = @needs_review,
sort_order = @sort_order,
updated_at = @updated_at
WHERE id = @id
`);
const deleteEvidenceLinksForEntityAndSource = db.prepare(`
DELETE FROM evidence_links
WHERE entity_type = @entity_type
AND entity_id = @entity_id
AND source_artifact_id = @source_artifact_id
`);
const listMilestonesBySourceArtifactId = db.prepare(`
SELECT *
FROM milestones
WHERE project_id = @project_id
AND source_artifact_id = @source_artifact_id
`);
const deleteMilestoneById = db.prepare(`
DELETE FROM milestones
WHERE id = @id
`);
const insertEvidenceLink = db.prepare(`
INSERT INTO evidence_links (
entity_type, entity_id, source_artifact_id, excerpt, line_start, line_end, confidence, reason, created_at
) VALUES (
@entity_type, @entity_id, @source_artifact_id, @excerpt, @line_start, @line_end, @confidence, @reason, @created_at
)
`);
const getGsdRequirementsArtifactByProjectId = db.prepare(`
SELECT *
FROM source_artifacts
WHERE project_id = ? AND artifact_type = 'gsd_requirements'
ORDER BY id ASC
LIMIT 1
`);
const getRequirementByProjectArtifactAndKey = db.prepare(`
SELECT *
FROM requirements
WHERE project_id = @project_id
AND source_artifact_id = @source_artifact_id
AND external_key = @external_key
LIMIT 1
`);
const getRequirementByProjectAndKey = db.prepare(`
SELECT *
FROM requirements
WHERE project_id = @project_id
AND external_key = @external_key
LIMIT 1
`);
const updateMilestoneProofLevel = db.prepare(`
UPDATE milestones
SET proof_level = @proof_level
WHERE id = @id
`);
const insertRequirement = db.prepare(`
INSERT INTO requirements (
project_id, external_key, title, description, status, validation, notes,
primary_owner, supporting_slices, source_artifact_id, created_at, updated_at
) VALUES (
@project_id, @external_key, @title, @description, @status, @validation, @notes,
@primary_owner, @supporting_slices, @source_artifact_id, @created_at, @updated_at
)
`);
const updateRequirement = db.prepare(`
UPDATE requirements
SET title = @title,
description = @description,
status = @status,
validation = @validation,
notes = @notes,
primary_owner = @primary_owner,
supporting_slices = @supporting_slices,
updated_at = @updated_at
WHERE id = @id
`);
const listRequirementsBySourceArtifactId = db.prepare(`
SELECT *
FROM requirements
WHERE project_id = @project_id
AND source_artifact_id = @source_artifact_id
`);
const deleteRequirementById = db.prepare(`
DELETE FROM requirements
WHERE id = @id
`);
const getGsdDecisionsArtifactByProjectId = db.prepare(`
SELECT *
FROM source_artifacts
WHERE project_id = ? AND artifact_type = 'gsd_decisions'
ORDER BY id ASC
LIMIT 1
`);
const getDecisionByProjectArtifactAndKey = db.prepare(`
SELECT *
FROM decisions
WHERE project_id = @project_id
AND source_artifact_id = @source_artifact_id
AND external_key = @external_key
LIMIT 1
`);
const insertDecision = db.prepare(`
INSERT INTO decisions (
project_id, external_key, scope, decision, choice, rationale, revisable,
when_context, source_artifact_id, created_at, updated_at
) VALUES (
@project_id, @external_key, @scope, @decision, @choice, @rationale, @revisable,
@when_context, @source_artifact_id, @created_at, @updated_at
)
`);
const updateDecision = db.prepare(`
UPDATE decisions
SET scope = @scope,
decision = @decision,
choice = @choice,
rationale = @rationale,
revisable = @revisable,
when_context = @when_context,
updated_at = @updated_at
WHERE id = @id
`);
const listDecisionsBySourceArtifactId = db.prepare(`
SELECT *
FROM decisions
WHERE project_id = @project_id
AND source_artifact_id = @source_artifact_id
`);
const deleteDecisionById = db.prepare(`
DELETE FROM decisions
WHERE id = @id
`);
// ── Scan paths ────────────────────────────────────────────────────────────────
const listEnabledScanPaths = db.prepare(`
SELECT * FROM scan_paths WHERE enabled = 1 ORDER BY path ASC
`);
const listAllScanPaths = db.prepare(`
SELECT * FROM scan_paths ORDER BY path ASC
`);
const getScanPathById = db.prepare(`
SELECT * FROM scan_paths WHERE id = ?
`);
const insertScanPath = db.prepare(`
INSERT INTO scan_paths (path, enabled, recursive, max_depth, created_at, updated_at)
VALUES (@path, @enabled, @recursive, @max_depth, @created_at, @updated_at)
`);
const updateScanPath = db.prepare(`
UPDATE scan_paths
SET path = @path,
enabled = @enabled,
recursive = @recursive,
max_depth = @max_depth,
updated_at = @updated_at
WHERE id = @id
`);
const deleteScanPath = db.prepare(`
DELETE FROM scan_paths WHERE id = @id
`);
function safeReadDir(dirPath) {
try {
return fs.readdirSync(dirPath, { withFileTypes: true });
} catch {
return [];
}
}
function exists(filePath) {
try {
fs.accessSync(filePath, fs.constants.F_OK);
return true;
} catch {
return false;
}
}
function slugify(value) {
return value
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '') || 'project';
}
function detectProjectType(projectRoot) {
if (exists(path.join(projectRoot, 'package.json'))) return 'web_node';
if (exists(path.join(projectRoot, 'pyproject.toml')) || exists(path.join(projectRoot, 'requirements.txt'))) return 'python';
if (exists(path.join(projectRoot, '.gsd')) || exists(path.join(projectRoot, 'README.md'))) return 'general';
return 'unknown';
}
function detectPrimaryLanguage(projectRoot) {
if (exists(path.join(projectRoot, 'package.json'))) return 'javascript/typescript';
if (exists(path.join(projectRoot, 'pyproject.toml')) || exists(path.join(projectRoot, 'requirements.txt'))) return 'python';
return null;
}
function detectPackageManager(projectRoot) {
if (exists(path.join(projectRoot, 'pnpm-lock.yaml'))) return 'pnpm';
if (exists(path.join(projectRoot, 'package-lock.json'))) return 'npm';
if (exists(path.join(projectRoot, 'yarn.lock'))) return 'yarn';
return null;
}
function detectFramework(projectRoot) {
const packageJsonPath = path.join(projectRoot, 'package.json');
if (!exists(packageJsonPath)) return null;
try {
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
const deps = {
...(pkg.dependencies ?? {}),
...(pkg.devDependencies ?? {}),
};
if (deps.next) return 'nextjs';
if (deps.vite) return 'vite';
if (deps.react) return 'react';
} catch {
return null;
}
return null;
}
function detectArtifacts(projectRoot) {
const now = new Date().toISOString();
const artifacts = [];
for (const rule of ARTIFACT_RULES) {
const absolutePath = path.join(projectRoot, rule.relativePath);
if (exists(absolutePath)) {
artifacts.push({
artifact_type: rule.artifactType,
path: absolutePath,
title: path.basename(absolutePath),
confidence: 1.0,
parse_status: 'detected',
last_seen_at: now,
created_at: now,
updated_at: now,
});
}
}
const roadmapDir = path.join(projectRoot, DOCS_ROADMAP_DIR);
if (exists(roadmapDir)) {
for (const entry of safeReadDir(roadmapDir)) {
if (entry.isFile()) {
const artifactPath = path.join(roadmapDir, entry.name);
artifacts.push({
artifact_type: 'generic_plan',
path: artifactPath,
title: entry.name,
confidence: 0.85,
parse_status: 'detected',
last_seen_at: now,
created_at: now,
updated_at: now,
});
}
}
}
// Register .gsd/milestones/ dir as a structured artifact when present —
// milestone directories are ground truth even when PROJECT.md is stale.
const gsdMilestonesDir = path.join(projectRoot, '.gsd', 'milestones');
if (exists(gsdMilestonesDir)) {
artifacts.push({
artifact_type: 'gsd_milestones_dir',
path: gsdMilestonesDir,
title: '.gsd/milestones',
confidence: 1.0,
parse_status: 'detected',
last_seen_at: now,
created_at: now,
updated_at: now,
});
// Walk .gsd/milestones for SUMMARY files and register each as a gsd_summary artifact.
// Pattern: M###-SUMMARY.md (milestone) and S##-SUMMARY.md (slice)
function walkForSummaries(dir, depth = 0) {
if (depth > 4) return; // milestones/M###/slices/S##/S##-SUMMARY.md = depth 3
for (const entry of safeReadDir(dir)) {
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkForSummaries(entryPath, depth + 1);
} else if (entry.isFile() && /^(M\d+|S\d+)-SUMMARY\.md$/.test(entry.name)) {
artifacts.push({
artifact_type: 'gsd_summary',
path: entryPath,
title: entry.name,
confidence: 1.0,
parse_status: 'detected',
last_seen_at: now,
created_at: now,
updated_at: now,
});
}
}
}
walkForSummaries(gsdMilestonesDir);
}
return artifacts;
}
function derivePlanningStatus(artifacts) {
const types = new Set(artifacts.map((artifact) => artifact.artifact_type));
if (
types.has('gsd_project') ||
types.has('gsd_requirements') ||
types.has('roadmap_md') ||
types.has('milestones_md') ||
types.has('gsd_milestones_dir')
) {
return 'structured';
}
if (artifacts.length > 0) {
return 'partial';
}
return 'none';
}
function isProjectCandidate(projectRoot) {
return PROJECT_MARKERS.some((marker) => exists(path.join(projectRoot, marker)));
}
function parseProjectId(rawProjectId) {
const projectId = Number(rawProjectId);
if (Number.isNaN(projectId)) {
return null;
}
return projectId;
}
function serializeProjectRow(project) {
return {
id: project.id,
name: project.name,
slug: project.slug,
rootPath: project.root_path,
repoType: project.repo_type,
projectType: project.project_type,
primaryLanguage: project.primary_language,
framework: project.framework,
packageManager: project.package_manager,
hasGit: Boolean(project.has_git),
planningStatus: project.planning_status,
artifactCount: project.artifact_count,
lastScannedAt: project.last_scanned_at,
createdAt: project.created_at,
updatedAt: project.updated_at,
};
}
function serializeMilestoneRow(milestone) {
return {
id: milestone.id,
projectId: milestone.project_id,
externalKey: milestone.external_key,
title: milestone.title,
description: milestone.description,
status: milestone.status,
proofLevel: milestone.proof_level ?? 'claimed',
origin: milestone.origin,
confidence: milestone.confidence,
needsReview: Boolean(milestone.needs_review),
sortOrder: milestone.sort_order,
sourceArtifactId: milestone.source_artifact_id,
createdAt: milestone.created_at,
updatedAt: milestone.updated_at,
};
}
function serializeSliceRow(slice) {
return {
id: slice.id,
projectId: slice.project_id,
milestoneId: slice.milestone_id,
externalKey: slice.external_key,
title: slice.title,
description: slice.description,
status: slice.status,
origin: slice.origin,
confidence: slice.confidence,
needsReview: Boolean(slice.needs_review),
sortOrder: slice.sort_order,
sourceArtifactId: slice.source_artifact_id,
createdAt: slice.created_at,
updatedAt: slice.updated_at,
};
}
function serializePlanningTaskRow(task) {
return {
id: task.id,
projectId: task.project_id,
milestoneId: task.milestone_id,
sliceId: task.slice_id,
externalKey: task.external_key,
title: task.title,
description: task.description,
status: task.status,
category: task.category,
priority: task.priority,
origin: task.origin,
confidence: task.confidence,
needsReview: Boolean(task.needs_review),
sourceArtifactId: task.source_artifact_id,
createdAt: task.created_at,
updatedAt: task.updated_at,
};
}
function serializeRequirementRow(requirement) {
return {
id: requirement.id,
projectId: requirement.project_id,
externalKey: requirement.external_key,
title: requirement.title,
description: requirement.description,
status: requirement.status,
validation: requirement.validation,
notes: requirement.notes,
primaryOwner: requirement.primary_owner,
supportingSlices: requirement.supporting_slices,
mayBeProven: false, // overridden at plan route time via filesystem check
sourceArtifactId: requirement.source_artifact_id,
createdAt: requirement.created_at,
updatedAt: requirement.updated_at,
};
}
function serializeDecisionRow(decision) {
return {
id: decision.id,
projectId: decision.project_id,
externalKey: decision.external_key,
scope: decision.scope,
decision: decision.decision,
choice: decision.choice,
rationale: decision.rationale,
revisable: decision.revisable,
whenContext: decision.when_context,
sourceArtifactId: decision.source_artifact_id,
createdAt: decision.created_at,
updatedAt: decision.updated_at,
};
}
function serializeImportRunRow(importRun) {
return {
id: importRun.id,
projectId: importRun.project_id,
status: importRun.status,
strategy: importRun.strategy,
artifactType: importRun.strategy,
startedAt: importRun.started_at,
completedAt: importRun.completed_at,
summary: importRun.summary,
warningsJson: importRun.warnings_json,
};
}
function computeWorkflowState({ milestones, requirements, decisions, continuity, readiness, latestImportRunsByArtifact, proofSummary }) {
// evidence: explicit signals that produced the phase and confidence — never empty if confidence < 1
const evidence = [];
// reasons: human-readable explanations for the phase choice
const reasons = [];
// --- Gather evidence signals ---
const hasMilestones = milestones.length > 0;
const hasRequirements = requirements.length > 0;
const hasDecisions = decisions.length > 0;
const hasAnyArtifacts = hasMilestones || hasRequirements || hasDecisions;
if (hasMilestones) {
evidence.push({ label: 'Milestones', value: `${milestones.length} imported` });
}
if (hasRequirements) {
evidence.push({ label: 'Requirements', value: `${requirements.length} imported` });
}
if (hasDecisions) {
evidence.push({ label: 'Decisions', value: `${decisions.length} imported` });
}
// Import recency signals
const now = Date.now();
const msPerDay = 24 * 60 * 60 * 1000;
let mostRecentImportAgeMs = Number.POSITIVE_INFINITY;
if (latestImportRunsByArtifact) {
const runs = [
latestImportRunsByArtifact.milestones,
latestImportRunsByArtifact.requirements,
latestImportRunsByArtifact.decisions,
].filter(Boolean);
for (const run of runs) {
const ts = run.completedAt ? Date.parse(run.completedAt) : Number.NaN;
if (!Number.isNaN(ts)) {
const ageMs = now - ts;
if (ageMs < mostRecentImportAgeMs) mostRecentImportAgeMs = ageMs;
}
}
}
const importIsRecent = mostRecentImportAgeMs <= 3 * msPerDay;
const importIsStale = mostRecentImportAgeMs > 7 * msPerDay;
if (Number.isFinite(mostRecentImportAgeMs)) {
const ageDays = Math.round(mostRecentImportAgeMs / msPerDay);
evidence.push({
label: 'Last import',
value: ageDays === 0 ? 'today' : ageDays === 1 ? '1 day ago' : `${ageDays} days ago`,
});
}
// Continuity signal — reads from the new structured shape: status 'fresh'|'stale'|'missing'
const continuityStatus = continuity?.status ?? 'missing';
evidence.push({ label: 'Continuity', value: continuityStatus });
// Readiness signal — overall workflow stack health
if (readiness) {
evidence.push({ label: 'Readiness', value: readiness.overallReadiness });
}
// --- Determine phase ---
let phase;
if (!hasAnyArtifacts) {
phase = 'no-data';