test_schema.py
60.8 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
"""U-001 tests: all tables build, and the constraints named in the Unit's
Done criterion (unique / foreign key / enum) are actually enforced.
U-034 (PH5, 2026-08-02) added `deployment`/`deploy_health_signal` (17 tables
total) and widened `bug_record.root_cause_category` to accept `core_engine`.
2026-08-08 added `work_graph_loop_limit_config` (18 tables total, Work
Graph self-planning + loop-back).
Run: python3 -m unittest src.test_schema -v
"""
import re
import sqlite3
import unittest
from src import schema
class SchemaCreationTest(unittest.TestCase):
def setUp(self):
self.conn = schema.connect(":memory:")
schema.create_schema(self.conn)
def tearDown(self):
self.conn.close()
def test_all_18_tables_created(self):
rows = self.conn.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
).fetchall()
actual = {row[0] for row in rows}
self.assertEqual(actual, set(schema.TABLE_NAMES))
self.assertEqual(len(schema.TABLE_NAMES), 18)
def test_schema_is_idempotent_to_reopen_on_disk(self):
# not required by the Done criterion, but a schema that only works once
# against :memory: would be a trap for every later Unit that opens a
# real db file -- cheap to check now.
import os
import tempfile
fd, path = tempfile.mkstemp(suffix=".sqlite3")
os.close(fd)
os.remove(path)
try:
conn = schema.connect(path)
schema.create_schema(conn)
conn.close()
conn2 = schema.connect(path)
rows = conn2.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
).fetchall()
conn2.close()
self.assertEqual({r[0] for r in rows}, set(schema.TABLE_NAMES))
finally:
if os.path.exists(path):
os.remove(path)
class ConstraintTestBase(unittest.TestCase):
def setUp(self):
self.conn = schema.connect(":memory:")
schema.create_schema(self.conn)
def tearDown(self):
self.conn.close()
def insert_project(self, project_id="proj-1", target_folder_path="/tmp/proj-1"):
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES (?, ?, ?, 1, 'active')",
(project_id, "Project One", target_folder_path),
)
self.conn.commit()
return project_id
def insert_task(self, task_id="task-1", project_id="proj-1", status="queued"):
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES (?, ?, 'implement snake game', 'goal', ?, 'planner')",
(task_id, project_id, status),
)
self.conn.commit()
return task_id
def insert_skill(self, skill_id="skill-1"):
self.conn.execute(
"INSERT INTO skill (skill_id, owner_org_node, file_path, current_git_commit_sha, source, status) "
"VALUES (?, 'coder', 'skills/skill-1/', 'abc123', 'new', 'active')",
(skill_id,),
)
self.conn.commit()
return skill_id
def insert_work_graph_run(self, run_id="run-1", task_id="task-1", status="planning"):
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) VALUES (?, ?, '{}', ?)",
(run_id, task_id, status),
)
self.conn.commit()
return run_id
class ProjectUniqueConstraintTest(ConstraintTestBase):
def test_duplicate_target_folder_path_rejected(self):
self.insert_project("proj-1", "/tmp/shared-path")
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-2', 'Project Two', '/tmp/shared-path', 1, 'active')"
)
def test_has_git_repo_boolean_check_rejects_out_of_range_value(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/p', 2, 'active')"
)
class WorkNodeExecutionEnumConstraintTest(ConstraintTestBase):
def setUp(self):
super().setUp()
self.insert_project()
self.insert_task()
self.insert_skill()
self.insert_work_graph_run()
def _insert_node_exec(self, status):
self.conn.execute(
"INSERT INTO work_node_execution "
"(node_exec_id, run_id, node_id, subagent_type, skill_ref, "
" input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-1', 'run-1', 'n1', 'coder', 'skill-1', 'in.json', 'out.json', '{}', ?)",
(status,),
)
def test_valid_status_accepted(self):
self._insert_node_exec("waiting_for_quota")
self.conn.commit()
row = self.conn.execute(
"SELECT status FROM work_node_execution WHERE node_exec_id = 'node-1'"
).fetchone()
self.assertEqual(row[0], "waiting_for_quota")
def test_invalid_status_rejected(self):
with self.assertRaises(sqlite3.IntegrityError):
self._insert_node_exec("not_a_real_status")
class ForeignKeyEnforcementTest(ConstraintTestBase):
def test_task_rejects_unknown_project_id(self):
with self.assertRaises(sqlite3.IntegrityError):
self.insert_task(task_id="task-1", project_id="does-not-exist")
def test_work_node_execution_rejects_unknown_skill_ref(self):
self.insert_project()
self.insert_task()
self.insert_work_graph_run()
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_node_execution "
"(node_exec_id, run_id, node_id, subagent_type, skill_ref, "
" input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-1', 'run-1', 'n1', 'coder', 'no-such-skill', 'in.json', 'out.json', '{}', 'pending')"
)
class WorkGraphRunActiveUniqueIndexTest(ConstraintTestBase):
"""Org Graph unification Phase 2c §2.2 (2026-08-12): only one active run
per task_id at a time now (narrowed from (task_id, org_node) -- a merged
graph means one task has ONE run spanning its whole lifecycle, not one
per org_node). Active = any status except 'done'/'failed' -- 'blocked'
now counts as active on purpose (a blocked run is resumed by appending
into the SAME row, never by inserting a fresh one)."""
def setUp(self):
super().setUp()
self.insert_project()
self.insert_task()
def test_second_active_run_for_same_task_rejected(self):
self.insert_work_graph_run("run-1", "task-1", status="running")
with self.assertRaises(sqlite3.IntegrityError):
self.insert_work_graph_run("run-2", "task-1", status="planning")
def test_blocked_run_still_counts_as_active(self):
self.insert_work_graph_run("run-1", "task-1", status="blocked")
with self.assertRaises(sqlite3.IntegrityError):
self.insert_work_graph_run("run-2", "task-1", status="planning")
def test_second_run_allowed_once_first_is_done(self):
self.insert_work_graph_run("run-1", "task-1", status="done")
self.insert_work_graph_run("run-2", "task-1", status="planning")
count = self.conn.execute(
"SELECT COUNT(*) FROM work_graph_run WHERE task_id = 'task-1'"
).fetchone()[0]
self.assertEqual(count, 2)
def test_second_run_allowed_once_first_is_failed(self):
self.insert_work_graph_run("run-1", "task-1", status="failed")
self.insert_work_graph_run("run-2", "task-1", status="planning")
count = self.conn.execute(
"SELECT COUNT(*) FROM work_graph_run WHERE task_id = 'task-1'"
).fetchone()[0]
self.assertEqual(count, 2)
class ArtifactUniqueConstraintTest(ConstraintTestBase):
def setUp(self):
super().setUp()
self.insert_project()
self.insert_task()
self.insert_work_graph_run()
def _insert_artifact(self, artifact_id):
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES (?, 'sdd', 'task-1', 'run-1', 'sdd.md', 'sha-1')",
(artifact_id,),
)
def test_duplicate_task_type_commit_rejected(self):
self._insert_artifact("artifact-1")
self.conn.commit()
with self.assertRaises(sqlite3.IntegrityError):
self._insert_artifact("artifact-2")
def test_new_test_artifact_types_accepted(self):
for artifact_type in (
"test_dataset", "test_script",
"validator_benchmark", "validator_test_dataset", "validator_test_script",
):
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES (?, ?, 'task-1', 'run-1', 'x.md', 'sha-1')",
("artifact-" + artifact_type, artifact_type),
)
self.conn.commit()
class MigrateExpandArtifactTypesTest(unittest.TestCase):
"""2026-08-06: real upgrade path for an already-populated database whose
artifact table still has the pre-expansion CHECK constraint."""
def setUp(self):
self.conn = schema.connect(":memory:")
# Simulate a pre-migration database: create the OLD schema by hand
# (not schema.create_schema(), which already has the new constraint).
old_sql = schema.SCHEMA_SQL.replace(
"'brd', 'prd', 'sdd', 'benchmark', 'bug_record', 'code_diff', 'test_report',\n"
" 'test_dataset', 'test_script',\n"
" 'validator_benchmark', 'validator_test_dataset', 'validator_test_script'",
"'brd', 'prd', 'sdd', 'benchmark', 'bug_record', 'code_diff', 'test_report'",
)
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'g', 'goal', 'queued', 'planner')"
)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-1', 'task-1', '{}', 'planning')"
)
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES ('art-1', 'brd', 'task-1', 'run-1', 'brd.md', 'sha-1')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_old_check_constraint_rejects_new_type_before_migration(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES ('art-2', 'test_script', 'task-1', 'run-1', 'x', 'sha-2')"
)
def test_migration_preserves_existing_rows_and_accepts_new_types(self):
schema.migrate_expand_artifact_types(self.conn)
row = self.conn.execute("SELECT artifact_type FROM artifact WHERE artifact_id = 'art-1'").fetchone()
self.assertEqual(row[0], "brd")
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES ('art-2', 'test_script', 'task-1', 'run-1', 'x', 'sha-2')"
)
self.conn.commit()
count = self.conn.execute("SELECT COUNT(*) FROM artifact").fetchone()[0]
self.assertEqual(count, 2)
def test_unique_index_still_enforced_after_migration(self):
schema.migrate_expand_artifact_types(self.conn)
self.conn.commit()
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES ('art-dup', 'brd', 'task-1', 'run-1', 'brd.md', 'sha-1')"
)
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_expand_artifact_types(self.conn)
schema.migrate_expand_artifact_types(self.conn) # must not raise / must not duplicate
count = self.conn.execute("SELECT COUNT(*) FROM artifact").fetchone()[0]
self.assertEqual(count, 1)
def test_noop_on_a_freshly_created_already_expanded_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_expand_artifact_types(fresh) # must not raise
fresh.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('p', 'P', '/tmp/p', 1, 'active')"
)
fresh.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('t', 'p', 'g', 'goal', 'queued', 'planner')"
)
fresh.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('r', 't', '{}', 'planning')"
)
fresh.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha) VALUES ('a', 'test_script', 't', 'r', 'x', 'sha')"
)
fresh.commit()
finally:
fresh.close()
class ExecutionLogFileUniqueConstraintTest(ConstraintTestBase):
def setUp(self):
super().setUp()
self.insert_project()
self.insert_task()
self.insert_skill()
self.insert_work_graph_run()
self.conn.execute(
"INSERT INTO work_node_execution "
"(node_exec_id, run_id, node_id, subagent_type, skill_ref, "
" input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-1', 'run-1', 'n1', 'coder', 'skill-1', 'in.json', 'out.json', '{}', 'running')"
)
self.conn.commit()
def test_second_log_file_for_same_node_exec_rejected(self):
self.conn.execute(
"INSERT INTO execution_log_file (log_file_id, node_exec_id, project_id, file_path, format, status) "
"VALUES ('log-1', 'node-1', 'proj-1', '/logs/node-1.jsonl', 'jsonl', 'active')"
)
self.conn.commit()
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO execution_log_file (log_file_id, node_exec_id, project_id, file_path, format, status) "
"VALUES ('log-2', 'node-1', 'proj-1', '/logs/node-1-again.jsonl', 'jsonl', 'active')"
)
class BugRecordRootCauseCategoryTest(ConstraintTestBase):
"""core_engine was PH5-scoped and deliberately excluded pre-U-034
(confirmed with user, 2026-07-30); U-034 (2026-08-02) widened the enum
to accept it -- 05 §5.8's self-target routing needs it as a real,
storable category, not just a documented intention."""
def _insert_bug(self, root_cause_category):
self.conn.execute(
"INSERT INTO bug_record (bug_id, source, description, root_cause_category, status) "
"VALUES ('bug-1', 'validator', 'wall collision misjudged', ?, 'open')",
(root_cause_category,),
)
def test_all_four_categories_accepted(self):
for category in ("planning", "coder", "skill_defect", "core_engine"):
with self.subTest(category=category):
conn = schema.connect(":memory:")
schema.create_schema(conn)
conn.execute(
"INSERT INTO bug_record (bug_id, source, description, root_cause_category, status) "
"VALUES ('bug-1', 'validator', 'x', ?, 'open')",
(category,),
)
conn.commit()
conn.close()
def test_unknown_category_still_rejected(self):
with self.assertRaises(sqlite3.IntegrityError):
self._insert_bug("not_a_real_category")
class DeploymentEnumConstraintTest(ConstraintTestBase):
def _insert_deployment(self, deployment_id, status):
self.conn.execute(
"INSERT INTO deployment (deployment_id, git_commit_hash, previous_commit_hash, status, "
"previous_instance_dir) VALUES (?, 'sha-new', 'sha-old', ?, '/tmp/prev-instance')",
(deployment_id, status),
)
def test_every_state_machine_status_accepted(self):
statuses = (
"staged", "candidate_starting", "health_check_running", "health_check_passed",
"health_check_failed", "cutover_in_progress", "live", "monitoring",
"anomaly_detected", "rollback_in_progress", "rolled_back", "rollback_failed",
"blocked_pending_human", "monitoring_window_clean", "finalized",
)
for status in statuses:
with self.subTest(status=status):
conn = schema.connect(":memory:")
schema.create_schema(conn)
conn.execute(
"INSERT INTO deployment (deployment_id, git_commit_hash, previous_commit_hash, status, "
"previous_instance_dir) VALUES ('d1', 'sha-new', 'sha-old', ?, '/tmp/prev-instance')",
(status,),
)
conn.commit()
conn.close()
def test_invalid_status_rejected(self):
with self.assertRaises(sqlite3.IntegrityError):
self._insert_deployment("d1", "not_a_real_status")
class DeploymentActiveUniqueIndexTest(ConstraintTestBase):
"""01-M 1.15: only one non-terminal deployment (not finalized/rolled_back/
blocked_pending_human) at a time -- concurrent self-modifying deploys
would corrupt the single Live/previous_instance_dir bookkeeping."""
def _insert_deployment(self, deployment_id, status):
self.conn.execute(
"INSERT INTO deployment (deployment_id, git_commit_hash, previous_commit_hash, status, "
"previous_instance_dir) VALUES (?, 'sha-new', 'sha-old', ?, '/tmp/prev-instance')",
(deployment_id, status),
)
def test_second_active_deployment_rejected(self):
self._insert_deployment("d1", "staged")
self.conn.commit()
with self.assertRaises(sqlite3.IntegrityError):
self._insert_deployment("d2", "candidate_starting")
def test_second_deployment_allowed_once_first_is_terminal(self):
for terminal_status in ("finalized", "rolled_back", "blocked_pending_human"):
with self.subTest(terminal_status=terminal_status):
conn = schema.connect(":memory:")
schema.create_schema(conn)
conn.execute(
"INSERT INTO deployment (deployment_id, git_commit_hash, previous_commit_hash, status, "
"previous_instance_dir) VALUES ('d1', 'sha-new', 'sha-old', ?, '/tmp/prev-instance')",
(terminal_status,),
)
conn.commit()
conn.execute(
"INSERT INTO deployment (deployment_id, git_commit_hash, previous_commit_hash, status, "
"previous_instance_dir) VALUES ('d2', 'sha-newer', 'sha-new', 'staged', '/tmp/prev-instance-2')"
)
conn.commit()
count = conn.execute("SELECT COUNT(*) FROM deployment").fetchone()[0]
conn.close()
self.assertEqual(count, 2)
class DeployHealthSignalTest(ConstraintTestBase):
def setUp(self):
super().setUp()
self.conn.execute(
"INSERT INTO deployment (deployment_id, git_commit_hash, previous_commit_hash, status, "
"previous_instance_dir) VALUES ('d1', 'sha-new', 'sha-old', 'health_check_running', "
"'/tmp/prev-instance')"
)
self.conn.commit()
def test_valid_signal_accepted(self):
self.conn.execute(
"INSERT INTO deploy_health_signal (signal_id, deployment_id, sampled_at, signal_type, status, detail) "
"VALUES ('sig-1', 'd1', '2026-08-02T00:00:00Z', 'process_alive', 'ok', 'pid 1234 alive')"
)
self.conn.commit()
row = self.conn.execute("SELECT status FROM deploy_health_signal WHERE signal_id = 'sig-1'").fetchone()
self.assertEqual(row[0], "ok")
def test_invalid_signal_type_rejected(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO deploy_health_signal (signal_id, deployment_id, sampled_at, signal_type, status) "
"VALUES ('sig-1', 'd1', '2026-08-02T00:00:00Z', 'not_a_real_signal', 'ok')"
)
def test_invalid_status_rejected(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO deploy_health_signal (signal_id, deployment_id, sampled_at, signal_type, status) "
"VALUES ('sig-1', 'd1', '2026-08-02T00:00:00Z', 'process_alive', 'not_a_real_status')"
)
def test_rejects_unknown_deployment_id(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO deploy_health_signal (signal_id, deployment_id, sampled_at, signal_type, status) "
"VALUES ('sig-1', 'no-such-deployment', '2026-08-02T00:00:00Z', 'process_alive', 'ok')"
)
class MigrateAddWorkGraphForkColumnsTest(unittest.TestCase):
"""D (2026-08-06): real upgrade path for an already-populated database
whose work_graph_run table predates the fork columns."""
def setUp(self):
self.conn = schema.connect(":memory:")
# Strip the fork columns (and their leading comment block) back out
# of work_graph_run's CREATE TABLE to simulate a pre-migration
# database, without hand-maintaining a second copy of the DDL text.
old_sql = re.sub(
r",\n( --[^\n]*\n)* parent_run_id TEXT REFERENCES work_graph_run\(run_id\),\n"
r" fork_of_node_exec_id TEXT REFERENCES work_node_execution\(node_exec_id\)\n\);",
"\n);",
schema.SCHEMA_SQL,
)
self.assertNotIn("parent_run_id", old_sql) # sanity: the substitution actually matched
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'g', 'goal', 'queued', 'planner')"
)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-1', 'task-1', '{}', 'done')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_migration_preserves_existing_rows_and_adds_nullable_columns(self):
schema.migrate_add_work_graph_fork_columns(self.conn)
row = self.conn.execute(
"SELECT status, parent_run_id, fork_of_node_exec_id FROM work_graph_run WHERE run_id = 'run-1'"
).fetchone()
self.assertEqual(row, ("done", None, None))
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_add_work_graph_fork_columns(self.conn)
schema.migrate_add_work_graph_fork_columns(self.conn) # must not raise
count = self.conn.execute("SELECT COUNT(*) FROM work_graph_run").fetchone()[0]
self.assertEqual(count, 1)
def test_noop_on_a_freshly_created_already_expanded_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_add_work_graph_fork_columns(fresh) # must not raise
cols = {row[1] for row in fresh.execute("PRAGMA table_info(work_graph_run)").fetchall()}
self.assertIn("parent_run_id", cols)
self.assertIn("fork_of_node_exec_id", cols)
finally:
fresh.close()
_OLD_WORK_GRAPH_RUN_BLOCK = """-- 1.3 work_graph_run
CREATE TABLE work_graph_run (
run_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES task(task_id),
org_node TEXT NOT NULL CHECK (org_node IN ('planner', 'coder', 'validator')),
graph_manifest TEXT NOT NULL,
orchestration_script_ref TEXT,
status TEXT NOT NULL CHECK (status IN (
'planning', 'running', 'merging', 'verifying',
'reflecting', 'blocked', 'done', 'failed'
)),
started_at TEXT,
completed_at TEXT,
result_artifact_refs TEXT
);
CREATE UNIQUE INDEX ux_work_graph_run_active ON work_graph_run(task_id, org_node)
WHERE status IN ('planning', 'running', 'merging', 'verifying');
"""
def _old_org_node_enum_schema_sql():
"""H (2026-08-06): simulates a pre-migration database whose 4
org_node-ish columns still have the old CHECK(x IN ('planner','coder',
'validator')) enum, and whose work_graph_run predates D's fork columns
too (migrate_relax_org_node_constraints depends on
migrate_add_work_graph_fork_columns having run, so the test fixture
should start from a database that's had NEITHER migration, same as a
real old production db would be).
2026-08-12 (Org Graph unification Phase 2c §2.1): work_graph_run.org_node
no longer exists in schema.SCHEMA_SQL at all (removed outright, not just
relaxed -- see migrate_drop_work_graph_run_org_node), so this function
can no longer derive the 'old' work_graph_run shape via regex
substitution the way it still does for owner_org_node/assigned_org_node/
agent_profile.org_node below (those 3 are unaffected by Phase 2c, still
present in SCHEMA_SQL). The 1.3 section is spliced out and replaced with
a hardcoded legacy block instead -- the historical shape this test
exercises no longer has a live counterpart to derive from."""
before, _, rest = schema.SCHEMA_SQL.partition("-- 1.3 work_graph_run")
_, _, after = rest.partition("-- 1.4 work_node_execution")
sql = before + _OLD_WORK_GRAPH_RUN_BLOCK + "-- 1.4 work_node_execution" + after
for column in ("owner_org_node", "assigned_org_node"):
sql = re.sub(
r"(?: --[^\n]*\n)* " + column + r" TEXT( NOT NULL)? CHECK \(" + column + r" != ''\)",
column + r" TEXT\1 CHECK (" + column + " IN ('planner', 'coder', 'validator'))",
sql,
)
sql = re.sub(
r"(?: --[^\n]*\n)* org_node TEXT PRIMARY KEY CHECK \(org_node != ''\)",
"org_node TEXT PRIMARY KEY CHECK (org_node IN ('planner', 'coder', 'validator'))",
sql,
)
return sql
class MigrateRelaxOrgNodeConstraintsTest(unittest.TestCase):
"""H (2026-08-06, Role Package abstraction): real upgrade path for an
already-populated database whose skill/task/work_graph_run/
agent_profile tables still enum-CHECK org_node to exactly
('planner', 'coder', 'validator')."""
def setUp(self):
old_sql = _old_org_node_enum_schema_sql()
self.assertNotIn("!= ''", old_sql) # sanity: the substitution actually matched
self.assertNotIn("parent_run_id", old_sql)
self.conn = schema.connect(":memory:")
self.conn.execute("PRAGMA foreign_keys = ON")
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'g', 'goal', 'queued', 'planner')"
)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status) "
"VALUES ('run-1', 'task-1', 'planner', '{}', 'done')"
)
self.conn.execute(
"INSERT INTO skill (skill_id, owner_org_node, file_path, current_git_commit_sha, source, status) "
"VALUES ('skill-1', 'planner', 'skills/x/', 'sha', 'new', 'active')"
)
self.conn.execute(
"INSERT INTO agent_profile (org_node, soul_file_path, migrated_from_profile, current_git_commit_sha) "
"VALUES ('planner', 'agents/planner/SOUL.md', 'planning', 'sha')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_old_schema_rejects_a_new_role(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-2', 'proj-1', 'g', 'goal', 'queued', 'newrole')"
)
def test_migration_preserves_existing_rows(self):
schema.migrate_relax_org_node_constraints(self.conn)
self.assertEqual(
self.conn.execute("SELECT task_id, assigned_org_node FROM task WHERE task_id = 'task-1'").fetchone(),
("task-1", "planner"),
)
self.assertEqual(
self.conn.execute("SELECT skill_id, owner_org_node FROM skill WHERE skill_id = 'skill-1'").fetchone(),
("skill-1", "planner"),
)
self.assertEqual(
self.conn.execute("SELECT run_id, org_node FROM work_graph_run WHERE run_id = 'run-1'").fetchone(),
("run-1", "planner"),
)
self.assertEqual(
self.conn.execute("SELECT org_node FROM agent_profile WHERE org_node = 'planner'").fetchone(),
("planner",),
)
def test_migration_accepts_a_new_role_afterward(self):
schema.migrate_relax_org_node_constraints(self.conn)
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-2', 'proj-1', 'g', 'goal', 'queued', 'newrole')"
)
self.conn.execute(
"INSERT INTO skill (skill_id, owner_org_node, file_path, current_git_commit_sha, source, status) "
"VALUES ('skill-2', 'newrole', 'skills/y/', 'sha', 'new', 'active')"
)
self.conn.execute(
"INSERT INTO agent_profile (org_node, soul_file_path, migrated_from_profile, current_git_commit_sha) "
"VALUES ('newrole', 'roles/newrole/SOUL.md', 'planning', 'sha')"
)
self.conn.commit()
self.assertEqual(self.conn.execute("SELECT COUNT(*) FROM task").fetchone()[0], 2)
def test_migration_still_rejects_empty_string(self):
schema.migrate_relax_org_node_constraints(self.conn)
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-2', 'proj-1', 'g', 'goal', 'queued', '')"
)
def test_ux_work_graph_run_active_still_enforced_after_rebuild(self):
schema.migrate_relax_org_node_constraints(self.conn)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status) "
"VALUES ('run-2', 'task-1', 'coder', '{}', 'running')"
)
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status) "
"VALUES ('run-3', 'task-1', 'coder', '{}', 'running')"
)
def test_task_indexes_survive_rebuild(self):
schema.migrate_relax_org_node_constraints(self.conn)
index_names = {
row[1] for row in self.conn.execute("PRAGMA index_list(task)").fetchall()
}
self.assertIn("idx_task_status", index_names)
self.assertIn("idx_task_assigned_org_node", index_names)
self.assertIn("idx_task_project_id", index_names)
def test_foreign_key_relationships_survive_rebuild(self):
# work_node_execution references both skill and work_graph_run --
# confirms the child tables (never rebuilt themselves) still see a
# valid parent after skill/work_graph_run were dropped and recreated.
schema.migrate_relax_org_node_constraints(self.conn)
self.conn.execute(
"INSERT INTO work_node_execution (node_exec_id, run_id, node_id, subagent_type, skill_ref, "
"input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-1', 'run-1', 'n1', 'planner', 'skill-1', 'in.json', 'out.json', '{}', 'done')"
)
self.conn.commit()
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_node_execution (node_exec_id, run_id, node_id, subagent_type, skill_ref, "
"input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-2', 'no-such-run', 'n1', 'planner', 'skill-1', 'in.json', 'out.json', '{}', 'done')"
)
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_relax_org_node_constraints(self.conn)
schema.migrate_relax_org_node_constraints(self.conn) # must not raise
count = self.conn.execute("SELECT COUNT(*) FROM task").fetchone()[0]
self.assertEqual(count, 1)
def test_foreign_keys_pragma_restored_after_migration(self):
schema.migrate_relax_org_node_constraints(self.conn)
self.assertEqual(self.conn.execute("PRAGMA foreign_keys").fetchone()[0], 1)
def test_noop_on_a_freshly_created_already_relaxed_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_relax_org_node_constraints(fresh) # must not raise
fresh.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
fresh.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'g', 'goal', 'queued', 'newrole')"
)
fresh.commit()
finally:
fresh.close()
class MigrateDropWorkGraphRunOrgNodeTest(unittest.TestCase):
"""Org Graph unification Phase 2c §2.1/§2.2 (2026-08-12): real upgrade
path for an already-populated database whose work_graph_run still has
the org_node column (with the OLDEST possible starting shape -- the
strict 3-value enum, same fixture as MigrateRelaxOrgNodeConstraintsTest
-- to also exercise this migration's own internal dependency call to
migrate_relax_org_node_constraints())."""
def setUp(self):
old_sql = _old_org_node_enum_schema_sql()
self.conn = schema.connect(":memory:")
self.conn.execute("PRAGMA foreign_keys = ON")
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'g', 'goal', 'queued', 'planner')"
)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status) "
"VALUES ('run-1', 'task-1', 'planner', '{}', 'done')"
)
self.conn.execute(
"INSERT INTO skill (skill_id, owner_org_node, file_path, current_git_commit_sha, source, status) "
"VALUES ('skill-1', 'planner', 'skills/x/', 'sha', 'new', 'active')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_org_node_column_actually_dropped(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
cols = {row[1] for row in self.conn.execute("PRAGMA table_info(work_graph_run)").fetchall()}
self.assertNotIn("org_node", cols)
def test_migration_preserves_existing_rows(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.assertEqual(
self.conn.execute(
"SELECT run_id, task_id, status FROM work_graph_run WHERE run_id = 'run-1'"
).fetchone(),
("run-1", "task-1", "done"),
)
def test_ux_work_graph_run_active_narrowed_to_task_id(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-2', 'task-1', '{}', 'running')"
)
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-3', 'task-1', '{}', 'running')"
)
def test_blocked_run_still_counts_as_active_after_migration(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-2', 'task-1', '{}', 'blocked')"
)
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-3', 'task-1', '{}', 'planning')"
)
def test_second_run_allowed_once_first_is_done(self):
# run-1 (seeded in setUp) is already status='done' -- a second run
# for the SAME task_id must be allowed.
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-2', 'task-1', '{}', 'planning')"
)
self.conn.commit()
count = self.conn.execute("SELECT COUNT(*) FROM work_graph_run WHERE task_id = 'task-1'").fetchone()[0]
self.assertEqual(count, 2)
def test_foreign_key_relationships_survive_rebuild(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.conn.execute(
"INSERT INTO work_node_execution (node_exec_id, run_id, node_id, subagent_type, skill_ref, "
"input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-1', 'run-1', 'n1', 'planner', 'skill-1', 'in.json', 'out.json', '{}', 'done')"
)
self.conn.commit()
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_node_execution (node_exec_id, run_id, node_id, subagent_type, skill_ref, "
"input_schema_ref, output_schema_ref, input_payload, status) "
"VALUES ('node-2', 'no-such-run', 'n1', 'planner', 'skill-1', 'in.json', 'out.json', '{}', 'done')"
)
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
schema.migrate_drop_work_graph_run_org_node(self.conn) # must not raise
count = self.conn.execute("SELECT COUNT(*) FROM work_graph_run").fetchone()[0]
self.assertEqual(count, 1)
def test_foreign_keys_pragma_restored_after_migration(self):
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.assertEqual(self.conn.execute("PRAGMA foreign_keys").fetchone()[0], 1)
def test_noop_on_a_freshly_created_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_drop_work_graph_run_org_node(fresh) # must not raise
fresh.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
fresh.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'g', 'goal', 'queued', 'planner')"
)
fresh.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-1', 'task-1', '{}', 'planning')"
)
fresh.commit()
finally:
fresh.close()
def test_duplicate_non_terminal_rows_per_task_reconciled_before_index(self):
# Real 2026-08-13 incident: pre-Phase-2c databases can have several
# non-terminal work_graph_run rows for the same task_id (one per
# org_node, before runs were merged). The narrowed unique index
# can't be created until only one non-terminal row per task_id
# remains -- this must not raise.
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status, started_at) "
"VALUES ('run-2', 'task-1', 'coder', '{}', 'running', '2026-08-01T00:00:00')"
)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status, started_at) "
"VALUES ('run-3', 'task-1', 'validator', '{}', 'planning', '2026-08-02T00:00:00')"
)
self.conn.commit()
schema.migrate_drop_work_graph_run_org_node(self.conn)
rows = self.conn.execute(
"SELECT run_id, status FROM work_graph_run WHERE task_id = 'task-1' AND run_id != 'run-1'"
).fetchall()
statuses = dict(rows)
# run-3 started latest among the non-terminal duplicates -> stays active.
self.assertEqual(statuses["run-3"], "planning")
self.assertEqual(statuses["run-2"], "failed")
# the narrowed index must have actually been created and be enforced.
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-4', 'task-1', '{}', 'running')"
)
def test_duplicate_reconciliation_uses_insertion_order_not_uuid_when_started_at_null(self):
# Real 2026-08-13 incident: every legacy duplicate row had
# started_at = NULL. A run_id-string tiebreak would pick among
# them by UUID value, unrelated to which one was actually created
# last -- e.g. 'aaaa...' sorts after 'zzzz...' alphabetically but
# was inserted first. rowid (SQLite's true insertion-order
# counter) must be used instead, so the row inserted LAST (run-2,
# despite its run_id sorting before run-3's alphabetically) is the
# one kept active.
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status) "
"VALUES ('aaa-run-3', 'task-1', 'validator', '{}', 'planning')"
)
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, org_node, graph_manifest, status) "
"VALUES ('zzz-run-2', 'task-1', 'coder', '{}', 'running')"
)
self.conn.commit()
schema.migrate_drop_work_graph_run_org_node(self.conn)
statuses = dict(
self.conn.execute(
"SELECT run_id, status FROM work_graph_run WHERE run_id IN ('aaa-run-3', 'zzz-run-2')"
).fetchall()
)
self.assertEqual(statuses["aaa-run-3"], "failed")
self.assertEqual(statuses["zzz-run-2"], "running")
def test_reentrant_after_partial_migration_missing_index_only(self):
# Real 2026-08-13 incident: executescript() commits each DDL
# statement individually, so a process crash between ALTER TABLE
# ... RENAME and CREATE UNIQUE INDEX leaves a database with the
# org_node column already gone but ux_work_graph_run_active never
# created. Re-running the migration against that exact state must
# finish the job, not silently no-op because "org_node" is already
# absent.
schema.migrate_drop_work_graph_run_org_node(self.conn)
self.conn.execute("DROP INDEX ux_work_graph_run_active")
self.conn.commit()
has_index = self.conn.execute(
"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'ux_work_graph_run_active'"
).fetchone()
self.assertIsNone(has_index) # sanity: simulated partial state matches the real incident
schema.migrate_drop_work_graph_run_org_node(self.conn)
has_index = self.conn.execute(
"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'ux_work_graph_run_active'"
).fetchone()
self.assertIsNotNone(has_index)
class MigrateAddWorkGraphLoopLimitConfigTest(unittest.TestCase):
"""2026-08-08: real upgrade path for an already-populated database that
predates work_graph_loop_limit_config (plain CREATE TABLE IF NOT
EXISTS, no CHECK constraint to rebuild around)."""
def setUp(self):
self.conn = schema.connect(":memory:")
old_sql = schema.SCHEMA_SQL.replace(
"-- 1.11.1 work_graph_loop_limit_config (Work Graph self-planning + loop-back,\n"
"-- docs/done/work-graph-self-planning-and-loop-back-design.md §6)\n"
"CREATE TABLE work_graph_loop_limit_config (\n"
" config_id TEXT PRIMARY KEY,\n"
" max_loop_attempts INTEGER NOT NULL,\n"
" updated_by TEXT,\n"
" updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP\n"
");\n\n",
"",
)
self.assertNotIn("work_graph_loop_limit_config", old_sql) # sanity: substitution matched
self.conn.executescript(old_sql)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_migration_creates_the_table(self):
schema.migrate_add_work_graph_loop_limit_config(self.conn)
self.conn.execute(
"INSERT INTO work_graph_loop_limit_config (config_id, max_loop_attempts, updated_by) "
"VALUES ('default', 3, 'test')"
)
self.conn.commit()
row = self.conn.execute(
"SELECT max_loop_attempts FROM work_graph_loop_limit_config WHERE config_id = 'default'"
).fetchone()
self.assertEqual(row[0], 3)
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_add_work_graph_loop_limit_config(self.conn)
schema.migrate_add_work_graph_loop_limit_config(self.conn) # must not raise
def test_noop_on_a_freshly_created_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_add_work_graph_loop_limit_config(fresh) # must not raise
finally:
fresh.close()
class MigrateAddLoopBackEventTypeTest(unittest.TestCase):
"""2026-08-08: real upgrade path for an already-populated database whose
execution_event table still has the pre-expansion CHECK constraint."""
def setUp(self):
self.conn = schema.connect(":memory:")
old_sql = schema.SCHEMA_SQL.replace(
"'log_appended', 'quota_wait_started', 'loop_back_triggered'",
"'log_appended', 'quota_wait_started'",
)
self.assertNotIn("loop_back_triggered", old_sql) # sanity: substitution matched
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, event_type, payload) "
"VALUES ('evt-1', 'proj-1', 'log_appended', '{}')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_old_check_constraint_rejects_new_type_before_migration(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, event_type, payload) "
"VALUES ('evt-2', 'proj-1', 'loop_back_triggered', '{}')"
)
def test_migration_preserves_existing_rows_and_accepts_new_type(self):
schema.migrate_add_loop_back_event_type(self.conn)
row = self.conn.execute("SELECT event_type FROM execution_event WHERE event_id = 'evt-1'").fetchone()
self.assertEqual(row[0], "log_appended")
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, event_type, payload) "
"VALUES ('evt-2', 'proj-1', 'loop_back_triggered', '{}')"
)
self.conn.commit()
count = self.conn.execute("SELECT COUNT(*) FROM execution_event").fetchone()[0]
self.assertEqual(count, 2)
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_add_loop_back_event_type(self.conn)
schema.migrate_add_loop_back_event_type(self.conn) # must not raise
def test_noop_on_a_freshly_created_already_expanded_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_add_loop_back_event_type(fresh) # must not raise
finally:
fresh.close()
class MigrateAddReviewingPlannerOutputStatusTest(unittest.TestCase):
"""2026-08-08 (Org Graph unification Phase 1): real upgrade path for an
already-populated database whose task table still has the
pre-expansion CHECK constraint."""
def setUp(self):
self.conn = schema.connect(":memory:")
old_sql = schema.SCHEMA_SQL.replace(
"'queued', 'planning_brd_prd_sdd', 'reviewing_planner_output', 'planning_failed',",
"'queued', 'planning_brd_prd_sdd', 'planning_failed',",
)
self.assertNotIn("reviewing_planner_output", old_sql) # sanity: substitution matched
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO task (task_id, project_id, goal_text, task_type, status, assigned_org_node) "
"VALUES ('task-1', 'proj-1', 'implement snake game', 'goal', 'queued', 'planner')"
)
# 2026-08-12 real-restart incident regression: task is a PARENT table --
# every real production database has months of child rows across these
# four tables REFERENCES task(task_id). Seeding at least one of each here
# is the actual fix for why the original migration's bug (DROP TABLE task
# under PRAGMA foreign_keys=ON trips FK enforcement the instant a
# referencing child row exists) went undetected by this test class --
# every test below previously ran against a task row with ZERO
# referencing children, so FK enforcement was never truly exercised.
self.conn.execute(
"INSERT INTO work_graph_run (run_id, task_id, graph_manifest, status) "
"VALUES ('run-1', 'task-1', '{}', 'done')"
)
self.conn.execute(
"INSERT INTO artifact (artifact_id, artifact_type, task_id, produced_by_run_id, "
"file_path, git_commit_sha, validation_status) "
"VALUES ('art-1', 'sdd', 'task-1', 'run-1', 'f.md', 'sha', 'passed')"
)
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, task_id, event_type, payload) "
"VALUES ('evt-1', 'proj-1', 'task-1', 'task_status_changed', '{}')"
)
self.conn.execute(
"INSERT INTO bug_record (bug_id, task_id, source, description, status) "
"VALUES ('bug-1', 'task-1', 'validator', 'real bug', 'open')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_old_check_constraint_rejects_new_status_before_migration(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"UPDATE task SET status = 'reviewing_planner_output' WHERE task_id = 'task-1'"
)
def test_migration_succeeds_with_real_foreign_key_referencing_child_rows(self):
# the actual regression: must not raise sqlite3.IntegrityError
# (FOREIGN KEY constraint failed) -- this is exactly what happened
# restarting the live production backend_server for real.
schema.migrate_add_reviewing_planner_output_status(self.conn)
for table, id_col, id_val in (
("work_graph_run", "run_id", "run-1"),
("artifact", "artifact_id", "art-1"),
("execution_event", "event_id", "evt-1"),
("bug_record", "bug_id", "bug-1"),
):
row = self.conn.execute(
"SELECT task_id FROM {} WHERE {} = ?".format(table, id_col), (id_val,)
).fetchone()
self.assertEqual(row[0], "task-1", "{} lost its task_id linkage after migration".format(table))
violations = self.conn.execute("PRAGMA foreign_key_check").fetchall()
self.assertEqual(violations, [])
def test_migration_preserves_existing_rows_and_accepts_new_status(self):
schema.migrate_add_reviewing_planner_output_status(self.conn)
row = self.conn.execute("SELECT status FROM task WHERE task_id = 'task-1'").fetchone()
self.assertEqual(row[0], "queued")
self.conn.execute("UPDATE task SET status = 'reviewing_planner_output' WHERE task_id = 'task-1'")
self.conn.commit()
row = self.conn.execute("SELECT status FROM task WHERE task_id = 'task-1'").fetchone()
self.assertEqual(row[0], "reviewing_planner_output")
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_add_reviewing_planner_output_status(self.conn)
schema.migrate_add_reviewing_planner_output_status(self.conn) # must not raise
def test_task_indexes_survive_rebuild(self):
schema.migrate_add_reviewing_planner_output_status(self.conn)
index_names = {
row[0] for row in self.conn.execute(
"SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='task'"
).fetchall()
}
self.assertIn("idx_task_status", index_names)
self.assertIn("idx_task_assigned_org_node", index_names)
self.assertIn("idx_task_project_id", index_names)
def test_noop_on_a_freshly_created_already_expanded_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_add_reviewing_planner_output_status(fresh) # must not raise
finally:
fresh.close()
class MigrateAddPlannerReviewVerdictEventTypeTest(unittest.TestCase):
"""2026-08-08 (Org Graph unification Phase 1): real upgrade path for an
already-populated database whose execution_event table still has the
pre-expansion CHECK constraint."""
def setUp(self):
self.conn = schema.connect(":memory:")
old_sql = schema.SCHEMA_SQL.replace(
"'log_appended', 'quota_wait_started', 'loop_back_triggered', 'planner_review_verdict'",
"'log_appended', 'quota_wait_started', 'loop_back_triggered'",
)
self.assertNotIn("planner_review_verdict", old_sql) # sanity: substitution matched
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO project (project_id, name, target_folder_path, has_git_repo, status) "
"VALUES ('proj-1', 'P', '/tmp/proj-1', 1, 'active')"
)
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, event_type, payload) "
"VALUES ('evt-1', 'proj-1', 'log_appended', '{}')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_old_check_constraint_rejects_new_type_before_migration(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, event_type, payload) "
"VALUES ('evt-2', 'proj-1', 'planner_review_verdict', '{}')"
)
def test_migration_preserves_existing_rows_and_accepts_new_type(self):
schema.migrate_add_planner_review_verdict_event_type(self.conn)
row = self.conn.execute("SELECT event_type FROM execution_event WHERE event_id = 'evt-1'").fetchone()
self.assertEqual(row[0], "log_appended")
self.conn.execute(
"INSERT INTO execution_event (event_id, project_id, event_type, payload) "
"VALUES ('evt-2', 'proj-1', 'planner_review_verdict', '{}')"
)
self.conn.commit()
count = self.conn.execute("SELECT COUNT(*) FROM execution_event").fetchone()[0]
self.assertEqual(count, 2)
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_add_planner_review_verdict_event_type(self.conn)
schema.migrate_add_planner_review_verdict_event_type(self.conn) # must not raise
def test_noop_on_a_freshly_created_already_expanded_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_add_planner_review_verdict_event_type(fresh) # must not raise
finally:
fresh.close()
class MigrateRelaxAgentProfileMigratedFromProfileTest(unittest.TestCase):
"""2026-08-08 (Org Graph unification Phase 1): real upgrade path for an
already-populated database whose agent_profile.migrated_from_profile is
still NOT NULL, surfaced by roles with no legacy Hermes profile (e.g.
planner_reviewer)."""
def setUp(self):
self.conn = schema.connect(":memory:")
old_sql = schema.SCHEMA_SQL.replace(
"migrated_from_profile TEXT CHECK (migrated_from_profile IN ('planning', 'code', 'qa')),\n"
" current_git_commit_sha TEXT NOT NULL\n"
");",
"migrated_from_profile TEXT NOT NULL CHECK (migrated_from_profile IN ('planning', 'code', 'qa')),\n"
" current_git_commit_sha TEXT NOT NULL\n"
");",
1, # only the first occurrence -- agent_profile's own table def, not skill's similarly-shaped column
)
self.assertIn("migrated_from_profile TEXT NOT NULL CHECK", old_sql) # sanity: substitution matched
self.conn.executescript(old_sql)
self.conn.commit()
self.conn.execute(
"INSERT INTO agent_profile (org_node, soul_file_path, migrated_from_profile, current_git_commit_sha) "
"VALUES ('validator', 'agents/validator/SOUL.md', 'qa', 'sha-1')"
)
self.conn.commit()
def tearDown(self):
self.conn.close()
def test_old_constraint_rejects_null_before_migration(self):
with self.assertRaises(sqlite3.IntegrityError):
self.conn.execute(
"INSERT INTO agent_profile (org_node, soul_file_path, migrated_from_profile, current_git_commit_sha) "
"VALUES ('planner_reviewer', 'agents/planner_reviewer/SOUL.md', NULL, 'sha-1')"
)
def test_migration_preserves_existing_rows_and_accepts_null(self):
schema.migrate_relax_agent_profile_migrated_from_profile(self.conn)
row = self.conn.execute(
"SELECT migrated_from_profile FROM agent_profile WHERE org_node = 'validator'"
).fetchone()
self.assertEqual(row[0], "qa")
self.conn.execute(
"INSERT INTO agent_profile (org_node, soul_file_path, migrated_from_profile, current_git_commit_sha) "
"VALUES ('planner_reviewer', 'agents/planner_reviewer/SOUL.md', NULL, 'sha-1')"
)
self.conn.commit()
row = self.conn.execute(
"SELECT migrated_from_profile FROM agent_profile WHERE org_node = 'planner_reviewer'"
).fetchone()
self.assertIsNone(row[0])
def test_idempotent_on_a_database_already_migrated(self):
schema.migrate_relax_agent_profile_migrated_from_profile(self.conn)
schema.migrate_relax_agent_profile_migrated_from_profile(self.conn) # must not raise
def test_noop_on_a_freshly_created_already_relaxed_database(self):
fresh = schema.connect(":memory:")
try:
schema.create_schema(fresh)
schema.migrate_relax_agent_profile_migrated_from_profile(fresh) # must not raise
finally:
fresh.close()
if __name__ == "__main__":
unittest.main()