Compare commits
1753
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
269e5a8f89 | ||
|
|
b11bb00094 | ||
|
|
ac3dc22a5e | ||
|
|
63b64f489c | ||
|
|
d17635201c | ||
|
|
08bebb2472 | ||
|
|
0ac8024a02 | ||
|
|
c86ed345a4 | ||
|
|
cf23cc1dd1 | ||
|
|
7177ae1264 | ||
|
|
20a1f53ae2 | ||
|
|
a0cdebce7e | ||
|
|
c14c9088e3 | ||
|
|
798c458954 | ||
|
|
ea57e97d58 | ||
|
|
92d2b60789 | ||
|
|
7778a1cea7 | ||
|
|
dad0889766 | ||
|
|
b9cc8d6ef1 | ||
|
|
0e0040832c | ||
|
|
cd8b9fc8b3 | ||
|
|
fa6073e2e1 | ||
|
|
4eb1b57933 | ||
|
|
4414f922fe | ||
|
|
6e42231cb1 | ||
|
|
bdf5aed665 | ||
|
|
0b62e2eb11 | ||
|
|
f9727d0853 | ||
|
|
d8e0ba3ea0 | ||
|
|
32e7844837 | ||
|
|
482d56233d | ||
|
|
6009720844 | ||
|
|
e26e55f389 | ||
|
|
4ac094fef6 | ||
|
|
a7e43b2281 | ||
|
|
cabc93bad3 | ||
|
|
5cda815626 | ||
|
|
32d17d3db5 | ||
|
|
6d35a87c5d | ||
|
|
dac514e6b6 | ||
|
|
96b4071cdb | ||
|
|
4ca3ff5191 | ||
|
|
7b9eef7ac2 | ||
|
|
9d66b104fe | ||
|
|
51ea084c87 | ||
|
|
6d33dd25ca | ||
|
|
c2132ee7dd | ||
|
|
0615fd7df1 | ||
|
|
7bf0a2ce15 | ||
|
|
2f774f8e80 | ||
|
|
2448212367 | ||
|
|
73d8597e01 | ||
|
|
30fa9443d6 | ||
|
|
fda6486233 | ||
|
|
cc92acf77b | ||
|
|
57aa76ac14 | ||
|
|
3b864044c6 | ||
|
|
b452303639 | ||
|
|
a9b1190a11 | ||
|
|
44fb34ad53 | ||
|
|
6245c547c2 | ||
|
|
24abab789e | ||
|
|
706c819cf3 | ||
|
|
1467717c12 | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
1603df97f5 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
2c33e9f28c | ||
|
|
c2776c2336 | ||
|
|
89c752c2b8 | ||
|
|
967193f737 | ||
|
|
e15026a12a | ||
|
|
5df6529caa | ||
|
|
3a12575b05 | ||
|
|
272e355ee9 | ||
|
|
e201350381 | ||
|
|
361df65ffb | ||
|
|
fc23be8184 | ||
|
|
c529c610e3 | ||
|
|
54a555c71b | ||
|
|
323ad3614f | ||
|
|
353acd9a27 | ||
|
|
d6e3326426 | ||
|
|
fb9764b8cb | ||
|
|
6a295b93ea | ||
|
|
9f19b4f06c | ||
|
|
84e1a91cab | ||
|
|
170f3201e7 | ||
|
|
9711e6c879 | ||
|
|
42450d51f1 | ||
|
|
22f021ed69 | ||
|
|
a4964b3b36 | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb | ||
|
|
2a29de7502 | ||
|
|
8c1605b383 | ||
|
|
90074e359f | ||
|
|
6155f5cf64 | ||
|
|
e3970e755b | ||
|
|
3c246f56b4 | ||
|
|
cebbe6ff19 | ||
|
|
e4a84a348e | ||
|
|
61e6d89d69 | ||
|
|
1b2f39d018 | ||
|
|
8c2d33abde | ||
|
|
60dc4af916 | ||
|
|
d389cfd4e3 | ||
|
|
6fc79737c3 | ||
|
|
cdd03591ef | ||
|
|
2fbb0565d7 | ||
|
|
a3dadc04bf | ||
|
|
1a59277dc8 | ||
|
|
6424197a19 | ||
|
|
8d4a8b4f31 | ||
|
|
23ab75e84a | ||
|
|
0488e47d9c | ||
|
|
0eba548282 | ||
|
|
68c0dd3b70 | ||
|
|
4cd958445f | ||
|
|
9f7861aadd | ||
|
|
9243ead1c3 | ||
|
|
5ba299d715 | ||
|
|
803c2b7738 | ||
|
|
28e7c9ae17 | ||
|
|
a9460bb772 | ||
|
|
5edf7c56ba | ||
|
|
90dc76b11e | ||
|
|
57d25c934b | ||
|
|
a26f0dc89f | ||
|
|
6ff6c13fc8 | ||
|
|
60c9ca0e33 | ||
|
|
ad2cb1dd57 | ||
|
|
674590e009 | ||
|
|
f2cb14e774 | ||
|
|
e042c25f56 | ||
|
|
90f1936fad | ||
|
|
42ff43915a | ||
|
|
834e5db458 | ||
|
|
8ce627ba91 | ||
|
|
9a78c6f2ba | ||
|
|
aab72f10c1 | ||
|
|
a76b7bbfb5 | ||
|
|
a51691a9b0 | ||
|
|
97de7d7e15 | ||
|
|
d7718e81e0 | ||
|
|
b88873508e | ||
|
|
58053d146b | ||
|
|
50767683b3 | ||
|
|
d1339f3846 | ||
|
|
faccdd4ca9 | ||
|
|
dd48bfd98c | ||
|
|
6d8d995621 | ||
|
|
b6c590af38 | ||
|
|
b51aef10c4 | ||
|
|
fc2cdeceb9 | ||
|
|
c637dfc454 | ||
|
|
6e9b43cb84 | ||
|
|
be56fa43b0 | ||
|
|
eb5eb0d9fa | ||
|
|
621616268a | ||
|
|
630df6b986 | ||
|
|
569b3e5959 | ||
|
|
d7ff7e7333 | ||
|
|
bd8e3ee008 | ||
|
|
c1d8a22f07 | ||
|
|
7b791895ad | ||
|
|
4c16c66368 | ||
|
|
4407a5a6b7 | ||
|
|
c7b375e9b0 | ||
|
|
abc253d97d | ||
|
|
ce11e6facd | ||
|
|
f1052dd8b1 | ||
|
|
e85144a58c | ||
|
|
defd9dfe20 | ||
|
|
8c03188c1c | ||
|
|
3e5f9f2cdd | ||
|
|
6888276f19 | ||
|
|
e06c33c38d | ||
|
|
5f860439e9 | ||
|
|
c9159b67b3 | ||
|
|
a1b727f62d | ||
|
|
fdc1e8b3a2 | ||
|
|
c8454ad88a | ||
|
|
336d176027 | ||
|
|
204984bf8c | ||
|
|
be4a38e578 | ||
|
|
f50a7cddc1 | ||
|
|
97487d9959 | ||
|
|
d2e38c5373 | ||
|
|
90bd5ee0c1 | ||
|
|
430ece4c0a | ||
|
|
4238a0e769 | ||
|
|
ff0f702c7c | ||
|
|
1cbe8a7a90 | ||
|
|
46fdc769d9 | ||
|
|
0cd0ed1a3d | ||
|
|
d53237cbd1 | ||
|
|
0e718855b8 | ||
|
|
731b1a67ac | ||
|
|
cdfecb36a6 | ||
|
|
f4ef356215 | ||
|
|
d60f5c6101 | ||
|
|
eacceb9e7b | ||
|
|
13a4789a5d | ||
|
|
b6e384fb27 | ||
|
|
d8bf307d22 | ||
|
|
d512deac84 | ||
|
|
32c7f90d9e | ||
|
|
2c16edd0cb | ||
|
|
708bc7091d | ||
|
|
7eb7b4f4a3 | ||
|
|
e01b1903de | ||
|
|
1dc36cef73 | ||
|
|
833c8ab7c6 | ||
|
|
5b1b35c773 | ||
|
|
ee3e2dae78 | ||
|
|
9c98cd60e8 | ||
|
|
48f88d5220 | ||
|
|
2910d9ff01 | ||
|
|
2b8e012924 | ||
|
|
49c23221d8 | ||
|
|
5ca7676661 | ||
|
|
c3e3e26844 | ||
|
|
1486a4a2b9 | ||
|
|
1e5f62801b | ||
|
|
ed6ba7439d | ||
|
|
f98448e872 | ||
|
|
bfe61741b8 | ||
|
|
4d3fcacd84 | ||
|
|
4d790f0064 | ||
|
|
3ecf3685ba | ||
|
|
716ae73c40 | ||
|
|
300d4d566a | ||
|
|
53a477c2e9 | ||
|
|
d84ebe8319 | ||
|
|
5a2c92e86d | ||
|
|
61aade9ea4 | ||
|
|
04f82ae1f3 | ||
|
|
ce0c20b840 | ||
|
|
fccecd8749 | ||
|
|
30a084c463 | ||
|
|
9d5ca2cb7c | ||
|
|
ac77fe452b | ||
|
|
4fbc4f9b20 | ||
|
|
779c237487 | ||
|
|
350e229f7a | ||
|
|
8112aff7c2 | ||
|
|
b9e22de6a3 | ||
|
|
f3b43a148b | ||
|
|
8331511b97 | ||
|
|
08650a7424 | ||
|
|
40d14647db | ||
|
|
cc69aef4dd | ||
|
|
71608142c2 | ||
|
|
bf1a6501c7 | ||
|
|
f7867addbe | ||
|
|
7a8bab5d9d | ||
|
|
06752526b3 | ||
|
|
d87ec967bf | ||
|
|
e55dd0067d | ||
|
|
8c3755aecc | ||
|
|
b4fe8faa1d | ||
|
|
515303edf2 | ||
|
|
20734d4a78 | ||
|
|
86db35ca61 | ||
|
|
97e5cd3bf7 | ||
|
|
b19fc1b87b | ||
|
|
2fa37ec183 | ||
|
|
db27502aff | ||
|
|
6c5fb7930d | ||
|
|
30acfa9c51 | ||
|
|
f58b6da230 | ||
|
|
9a1c4875a3 | ||
|
|
7eda6ba5fc | ||
|
|
c00e721c04 | ||
|
|
b0a3a50448 | ||
|
|
79c57170c7 | ||
|
|
3900c45f25 | ||
|
|
8d61172f8b | ||
|
|
dc82f792c3 | ||
|
|
335e0b59ea | ||
|
|
2fbbe68c24 | ||
|
|
65385c0281 | ||
|
|
6d2dae0627 | ||
|
|
10a8d3fbd9 | ||
|
|
0ad1e9d9e4 | ||
|
|
2f8d3baa88 | ||
|
|
6b74476322 | ||
|
|
d9e9539862 | ||
|
|
7118e43d16 | ||
|
|
4e8ee13d8f | ||
|
|
b17b6d50c5 | ||
|
|
ccf8331600 | ||
|
|
ffae12f329 | ||
|
|
01cd564557 | ||
|
|
4ee719a094 | ||
|
|
01492ebd3b | ||
|
|
93fd972108 | ||
|
|
df1540f3ac | ||
|
|
d5a72d5be1 | ||
|
|
742dd7af0d | ||
|
|
5c1ac92257 | ||
|
|
8bfdacf206 | ||
|
|
b6302784f8 | ||
|
|
7fcc993eae | ||
|
|
9544e72d08 | ||
|
|
938b19a6bb | ||
|
|
3b56dc17a5 | ||
|
|
d2c0a6a48f | ||
|
|
1cf3647da6 | ||
|
|
53d0107759 | ||
|
|
60b16d1f28 | ||
|
|
ab0baaa886 | ||
|
|
6821946ccc | ||
|
|
753bc4672d | ||
|
|
e29ad7604b | ||
|
|
12259adb5d | ||
|
|
cdaba7fa8b | ||
|
|
fbf6263876 | ||
|
|
c08b968f4e | ||
|
|
d9f59be704 | ||
|
|
a4446e263d | ||
|
|
494350cc0b | ||
|
|
7dc182337c | ||
|
|
13917df1fe | ||
|
|
5d4e2fae01 | ||
|
|
3e01c4bc57 | ||
|
|
20f37f367a | ||
|
|
804d44cfb1 | ||
|
|
c7f7e8c38d | ||
|
|
1161529645 | ||
|
|
0651af92b8 | ||
|
|
52a24c8902 | ||
|
|
30034ecedc | ||
|
|
1fcc57af13 | ||
|
|
e95b57dc26 | ||
|
|
9d38de8628 | ||
|
|
3bdaa6e100 | ||
|
|
b7b00bfb9d | ||
|
|
ae2b523503 | ||
|
|
9198a64c3d | ||
|
|
75b3b3c48a | ||
|
|
d62855cd7d | ||
|
|
c7539b92f5 | ||
|
|
b7ff82862e | ||
|
|
b489ea52a8 | ||
|
|
3a5ec9464b | ||
|
|
e56bb200fa | ||
|
|
c2ca9de33a | ||
|
|
60b546cf01 | ||
|
|
4b73827334 | ||
|
|
a5efb7cb6b | ||
|
|
8f9911f79d | ||
|
|
689a882045 | ||
|
|
85fe62d402 | ||
|
|
708d5383a9 | ||
|
|
5cd2744100 | ||
|
|
d12da198ad | ||
|
|
d0a7d18cdb | ||
|
|
71ea5fa1ab | ||
|
|
9d5e632d4d | ||
|
|
c2d44a312c | ||
|
|
de8bdc10fa | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 | ||
|
|
dbb184bb8a | ||
|
|
3a0623f1cd | ||
|
|
cd91ec75f3 | ||
|
|
d4ba9e9618 | ||
|
|
c1792bc9a6 | ||
|
|
1b4317ec35 | ||
|
|
f452d63fef | ||
|
|
18a49abcec | ||
|
|
85d5df6256 | ||
|
|
b5b769dddf | ||
|
|
3c7862edd7 | ||
|
|
d8fe3d72c8 | ||
|
|
70ec39ae80 | ||
|
|
3d9e8dea7d | ||
|
|
f7c422d581 | ||
|
|
dd739c880d | ||
|
|
6c6740e381 | ||
|
|
29150b5736 | ||
|
|
07c6d70b91 | ||
|
|
50bc18b208 | ||
|
|
63d42a5e58 | ||
|
|
9b43123ba2 | ||
|
|
17fb0e4a9a | ||
|
|
43e8bbd7ae | ||
|
|
52c77c1ec4 | ||
|
|
d6eb386e3d | ||
|
|
d25090cf6d | ||
|
|
ae39bacf0e | ||
|
|
1ea17026ee | ||
|
|
649f4328ea | ||
|
|
7db034905b | ||
|
|
57f6bf7edb | ||
|
|
0baf1986e8 | ||
|
|
ae7e88b0e0 | ||
|
|
1916ac6d55 | ||
|
|
343061a053 | ||
|
|
0b40ea62e1 | ||
|
|
a4757c2656 | ||
|
|
3efabdcd3a | ||
|
|
c5f7cd40ba | ||
|
|
e2db800f7c | ||
|
|
31533466b0 | ||
|
|
acc41f4742 | ||
|
|
6b6a9c4081 | ||
|
|
ae922761c3 | ||
|
|
0425b5510d | ||
|
|
0de927dfc6 | ||
|
|
e39cfb89f8 | ||
|
|
b14e89f11a | ||
|
|
96073b6bac | ||
|
|
bf75071f40 | ||
|
|
a1d2f75253 | ||
|
|
7f741a56d1 | ||
|
|
cc9e81ac93 | ||
|
|
238715fd6f | ||
|
|
b03bc4b52d | ||
|
|
aca14507f7 | ||
|
|
04f7f32ace | ||
|
|
a3422a9bb5 | ||
|
|
22f9f3058b | ||
|
|
983a8c7fa6 | ||
|
|
de58ec8e24 | ||
|
|
8e6f4229da | ||
|
|
38ea6d483e | ||
|
|
0e4a43519f | ||
|
|
3ea6adf17d | ||
|
|
a56496c7f2 | ||
|
|
b76f161d55 | ||
|
|
75257d64e9 | ||
|
|
e1ce9f8500 | ||
|
|
602148f8fe | ||
|
|
92be60e7c1 | ||
|
|
0d6e9e9add | ||
|
|
8ab58a0b26 | ||
|
|
6f42bd9c88 | ||
|
|
5b26bd408b | ||
|
|
c04d15d3be | ||
|
|
9da430c828 | ||
|
|
a084fbbc0a | ||
|
|
b870a6e349 | ||
|
|
e1cb19b55b | ||
|
|
94fc117561 | ||
|
|
113b9d84c7 | ||
|
|
f60def2054 | ||
|
|
eda163ca17 | ||
|
|
3579005114 | ||
|
|
af3dfd229e | ||
|
|
969e6d274c | ||
|
|
769bdd251d | ||
|
|
295b9db113 | ||
|
|
b5a62504d4 | ||
|
|
ec18938bf9 | ||
|
|
5ae77c0d63 | ||
|
|
300f7fd11d | ||
|
|
53042f47f8 | ||
|
|
6ce6f678b5 | ||
|
|
a74dfd4f3c | ||
|
|
49c1b64687 | ||
|
|
dfdb5a46db | ||
|
|
b0fa60a121 | ||
|
|
348a9140e9 | ||
|
|
9fc485afaf | ||
|
|
a6edad1974 | ||
|
|
203f58e456 | ||
|
|
52ae8e88df | ||
|
|
80b40ce96a | ||
|
|
4c262c4b4e | ||
|
|
4f3d00f063 | ||
|
|
37bf0f0d1d | ||
|
|
6a1c4da528 | ||
|
|
dca93d0ee8 | ||
|
|
1288909b66 | ||
|
|
30d36b8c48 | ||
|
|
e4643eccc7 | ||
|
|
4956415f7f | ||
|
|
f5849f7d78 | ||
|
|
6e6163255d | ||
|
|
b440dd1812 | ||
|
|
d78e02cd0b | ||
|
|
f0116e44b6 | ||
|
|
bd851c0203 | ||
|
|
a04c09a190 | ||
|
|
e3f1405884 | ||
|
|
b3e8c0334b | ||
|
|
e3accd6e95 | ||
|
|
cf07d06321 | ||
|
|
31268945f8 | ||
|
|
6b3050ee74 | ||
|
|
83f0cc9e31 | ||
|
|
e6330ead82 | ||
|
|
6d1d513032 | ||
|
|
4f0f24f055 | ||
|
|
d1e85c4e8f | ||
|
|
ea20e80021 | ||
|
|
9e632f5cec | ||
|
|
4120e94598 | ||
|
|
34bb18c8cf | ||
|
|
90eea047a9 | ||
|
|
f92e1e1b06 | ||
|
|
556c42452c | ||
|
|
7e20b23e7e | ||
|
|
b83e9c95e4 | ||
|
|
a41f4895ce | ||
|
|
d15909af15 | ||
|
|
447236d51f | ||
|
|
5165b8c333 | ||
|
|
8fc317939f | ||
|
|
16c69ba7ff | ||
|
|
e64c19f1af | ||
|
|
6ab8f93a23 | ||
|
|
b793401aee | ||
|
|
3c32bc8fd1 | ||
|
|
6efdf67e15 | ||
|
|
39371c6012 | ||
|
|
99efaa0faa | ||
|
|
ff03673ff8 | ||
|
|
6b9feb1bd3 | ||
|
|
e0f3abd1a4 | ||
|
|
34ec8a86fb | ||
|
|
932df4ed17 | ||
|
|
63859aa072 | ||
|
|
7bfacd55d8 | ||
|
|
271d65e047 | ||
|
|
aa8b9f2286 | ||
|
|
073eb389d3 | ||
|
|
825263b6f9 | ||
|
|
25b02f4ba2 | ||
|
|
131234be3f | ||
|
|
7455472c34 | ||
|
|
9d919d0bb8 | ||
|
|
aa219be713 | ||
|
|
dd32f52655 | ||
|
|
31b52acc8d | ||
|
|
466d8ee5b0 | ||
|
|
11f40556de | ||
|
|
1b440329f4 | ||
|
|
85f570a413 | ||
|
|
1bcfc88f58 | ||
|
|
2ba58076fa | ||
|
|
26f3c80250 | ||
|
|
c27109cc20 | ||
|
|
ca835c2508 | ||
|
|
7979036cd1 | ||
|
|
a74ed8ed32 | ||
|
|
2ea043e73b | ||
|
|
6c79039ce7 | ||
|
|
449e1aaa48 | ||
|
|
9316b57f9f | ||
|
|
d9c39e4d30 | ||
|
|
f3957fd473 | ||
|
|
22384ae977 | ||
|
|
499f1463d5 | ||
|
|
a2ff50dbba | ||
|
|
166bce0389 | ||
|
|
1498335e39 | ||
|
|
25c9d267ac | ||
|
|
536dcad19e | ||
|
|
0e38870647 | ||
|
|
9b604bcae1 | ||
|
|
35721d9a08 | ||
|
|
f4c9418d40 | ||
|
|
02dd47ea31 | ||
|
|
aca0fa4e5b | ||
|
|
0576820755 | ||
|
|
cb3211c8f3 | ||
|
|
826965978b | ||
|
|
623e471a02 | ||
|
|
91a03e0747 | ||
|
|
d501ebe877 | ||
|
|
3772fa127c | ||
|
|
92e340d80c | ||
|
|
59e9c647b7 | ||
|
|
d7969264de | ||
|
|
f7748a0d65 | ||
|
|
0ce7e56e43 | ||
|
|
350d76ee14 | ||
|
|
6d7fe2eeb7 | ||
|
|
460d9c3eb9 | ||
|
|
cb8015a34d | ||
|
|
8f50ca8e2c | ||
|
|
4ceabac764 | ||
|
|
5e5ad3c7a7 | ||
|
|
7a3f21e7ca | ||
|
|
17b43960e8 | ||
|
|
e5c7ac5a8c | ||
|
|
a480f07241 | ||
|
|
1eb6fcea84 | ||
|
|
4ef361da73 | ||
|
|
c07ac592d8 | ||
|
|
d649ccf715 | ||
|
|
f54f4385e5 | ||
|
|
e25ce07cc2 | ||
|
|
532a1d891d | ||
|
|
9e2f7129e3 | ||
|
|
a4298f1ceb | ||
|
|
86c94b4852 | ||
|
|
69d9a659a3 | ||
|
|
9acf46a76d | ||
|
|
44b39fe2ec | ||
|
|
02903f2db8 | ||
|
|
22b7d8c524 | ||
|
|
fe2fde5172 | ||
|
|
7da6522fb8 | ||
|
|
08e6d4cfbf | ||
|
|
35822884d1 | ||
|
|
2769c2e42d | ||
|
|
334265e87b | ||
|
|
dbebc387dd | ||
|
|
5cf83ffe8f | ||
|
|
969e8ea4fa | ||
|
|
ada410bccf | ||
|
|
00b5c3e1b3 | ||
|
|
188df6da07 | ||
|
|
0d55a42840 | ||
|
|
0ee302e24d | ||
|
|
d5b7690f95 | ||
|
|
8d1d699f88 | ||
|
|
b0b7b38da1 | ||
|
|
fd3b96b487 | ||
|
|
aa2d385a62 | ||
|
|
e25db3a572 | ||
|
|
b8305afa29 | ||
|
|
b7c89cf496 | ||
|
|
3a1daa87ac | ||
|
|
055897f0ea | ||
|
|
40b3a80034 | ||
|
|
7eefb2eb1d | ||
|
|
3bc8508de8 | ||
|
|
355eb2dade | ||
|
|
f6978db605 | ||
|
|
de05b0c94e | ||
|
|
6d1505c9fb | ||
|
|
306ec4bb84 | ||
|
|
3b98fe3548 | ||
|
|
66c326b8c4 | ||
|
|
8dbcf92a0d | ||
|
|
37965da01d | ||
|
|
57b59b5bf2 | ||
|
|
20f346d8ef | ||
|
|
c83bc5d48a | ||
|
|
d138a0bc31 | ||
|
|
11fa703852 | ||
|
|
d53e02b981 | ||
|
|
6e6bcd8450 | ||
|
|
6164a937ae | ||
|
|
c01b90a8fd | ||
|
|
047eb4e29a | ||
|
|
9c916d6caa | ||
|
|
35bc0902ae | ||
|
|
fa9bcbc053 | ||
|
|
a15194f649 | ||
|
|
2b623b54ff | ||
|
|
308dd659da | ||
|
|
9df3c64021 | ||
|
|
8ac57f7944 | ||
|
|
29cb917ac4 | ||
|
|
9c64f12ea0 | ||
|
|
0f184c28b0 | ||
|
|
a3b1df5224 | ||
|
|
4e0c003e78 | ||
|
|
60387f67e9 | ||
|
|
ce94feeea1 | ||
|
|
39ca3ee858 | ||
|
|
52a6067802 | ||
|
|
721b6b4c6f | ||
|
|
40009735ee | ||
|
|
df9d34004f | ||
|
|
f297e30e4c | ||
|
|
a7a44d0662 | ||
|
|
d8d329691a | ||
|
|
54179c86b8 | ||
|
|
8dba2d6484 | ||
|
|
ed6b7fbf27 | ||
|
|
b991b9b9e6 | ||
|
|
505db9f696 | ||
|
|
2d87574e62 | ||
|
|
b2cca674df | ||
|
|
549043863a | ||
|
|
b7df3dfca0 | ||
|
|
6891c77d3e | ||
|
|
d90e15d1d7 | ||
|
|
e0117b271a | ||
|
|
188a40c315 | ||
|
|
7a08fcf2e8 | ||
|
|
19d47408a5 | ||
|
|
3e07f5a6a4 | ||
|
|
d22c6f5280 | ||
|
|
5e13f53571 | ||
|
|
f9580ff088 | ||
|
|
5e1dd56d2c | ||
|
|
68061af042 | ||
|
|
28cb9db20b | ||
|
|
7968f278ee | ||
|
|
44afe784a3 | ||
|
|
9ff31f8c35 | ||
|
|
409ff90a14 | ||
|
|
0d280262f6 | ||
|
|
c9b07d665d | ||
|
|
2e42f3fdf6 | ||
|
|
008ac5c3e5 | ||
|
|
9dcea68bce | ||
|
|
5f7ec73a22 | ||
|
|
569fea87a9 | ||
|
|
33dadb5aec | ||
|
|
d18e43b674 | ||
|
|
6f699346e4 | ||
|
|
f5ecca4480 | ||
|
|
cadd708646 | ||
|
|
5f7becf386 | ||
|
|
9b29be916b | ||
|
|
047a0a697c | ||
|
|
77fcad3586 | ||
|
|
801b83e937 | ||
|
|
f2205bdc42 | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 | ||
|
|
5467d11980 | ||
|
|
1f4a3f65bf | ||
|
|
26cc1fffb3 | ||
|
|
97880e8870 | ||
|
|
b80e8476b8 | ||
|
|
e0e01b4a54 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b | ||
|
|
a3dadf311e | ||
|
|
e3004ae806 | ||
|
|
9385314d26 | ||
|
|
a3f292770e | ||
|
|
2028d57e88 | ||
|
|
3405a64dd8 | ||
|
|
1cba2f64d3 | ||
|
|
1a05d8ca1a | ||
|
|
cf9f236c80 | ||
|
|
e82b987386 | ||
|
|
ea9e61b266 | ||
|
|
e32077cee7 | ||
|
|
5d9eb18312 | ||
|
|
abb84c09e3 | ||
|
|
65d797c13e | ||
|
|
7c0849fe2e | ||
|
|
592c234fd5 | ||
|
|
66d76b5d02 | ||
|
|
528bb2a1fa | ||
|
|
869789b4ed | ||
|
|
9bedd7140c | ||
|
|
70f5dfcef7 | ||
|
|
9847e9b621 | ||
|
|
b547fee77e | ||
|
|
7b3cdc6a8c | ||
|
|
386eb18a58 | ||
|
|
7372184d06 | ||
|
|
d9ded65dfe | ||
|
|
2aa73985ea | ||
|
|
5b3b31b6e6 | ||
|
|
b7559c4678 | ||
|
|
b96308fc5a | ||
|
|
72b7f90c50 | ||
|
|
1ec346c22e | ||
|
|
28e481eb24 | ||
|
|
b1934b925a | ||
|
|
8244fb80e6 | ||
|
|
afc3924393 | ||
|
|
11d456f6c8 | ||
|
|
a221542921 | ||
|
|
226ed997e1 | ||
|
|
c6f57a1064 | ||
|
|
340dbbb36e | ||
|
|
53a552e80d | ||
|
|
cf2c628bc0 | ||
|
|
e0874b651d | ||
|
|
12347082ef | ||
|
|
740d7a3216 | ||
|
|
cd7980b457 | ||
|
|
f2cd53f232 | ||
|
|
04a1ae77e6 | ||
|
|
6de4b47ecb | ||
|
|
27c2b145f8 | ||
|
|
8515f02770 | ||
|
|
e9ed849b53 | ||
|
|
e8f5b4ad5b | ||
|
|
752f96e9ae | ||
|
|
1b272fd709 | ||
|
|
9013c07f6d | ||
|
|
085340588a | ||
|
|
48481aa923 | ||
|
|
da107f315c | ||
|
|
d2822a8883 | ||
|
|
ae3ea3980d | ||
|
|
915a0548c0 | ||
|
|
5ce5472bc3 | ||
|
|
9ea443d73a | ||
|
|
60f7ae86bb | ||
|
|
867cf4cf09 | ||
|
|
ae6f9715c6 | ||
|
|
b92c78f552 | ||
|
|
801dfe5b41 | ||
|
|
823d69f621 | ||
|
|
4963fccb05 | ||
|
|
dd89d5ce1a | ||
|
|
9132c37c86 | ||
|
|
b9c7ea0581 | ||
|
|
556a195c9d | ||
|
|
80b282ece7 | ||
|
|
d15075b32d | ||
|
|
9f6686a13d | ||
|
|
c6ff7c0d5b | ||
|
|
a9e5a84c03 | ||
|
|
67ca528fea | ||
|
|
6d9b21c5d0 | ||
|
|
ddffdfc095 | ||
|
|
a58290ed79 | ||
|
|
3488ca3570 | ||
|
|
c542ce3369 | ||
|
|
15f0be848d | ||
|
|
1c3fa67374 | ||
|
|
0ac59d569d | ||
|
|
d8aa2f85df | ||
|
|
64d6938cf4 | ||
|
|
0a88719a3a | ||
|
|
0bc94bc24e | ||
|
|
19eb9e7227 | ||
|
|
aa5521dcfb | ||
|
|
2d03847ccd | ||
|
|
d303ac39cb | ||
|
|
48fc85e7fe | ||
|
|
0ea639196a | ||
|
|
6f51725732 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 | ||
|
|
a60daa1c76 | ||
|
|
bc1024caf0 | ||
|
|
a1c428b6e2 | ||
|
|
00f3efb95b | ||
|
|
7f3387a86c | ||
|
|
5462d50177 | ||
|
|
f82bae1668 | ||
|
|
9e60597174 | ||
|
|
afc807ac3f | ||
|
|
58ba4f1263 | ||
|
|
5513845fd5 | ||
|
|
33773ff17e | ||
|
|
64d21bd6d2 | ||
|
|
5210a833a5 | ||
|
|
5b1d5c1220 | ||
|
|
f4617e7b19 | ||
|
|
c426452239 | ||
|
|
73b2f255a9 | ||
|
|
ce463a5360 | ||
|
|
52fa6a7333 | ||
|
|
04298962be | ||
|
|
61f983098b | ||
|
|
32c1f98a02 | ||
|
|
5851b8aca4 | ||
|
|
3e2df5a782 | ||
|
|
f0cdaf94c2 | ||
|
|
48196e67a7 | ||
|
|
80a176fe1f | ||
|
|
42ea7cfae1 | ||
|
|
d2e6c82709 | ||
|
|
23b3f0c3d0 | ||
|
|
e08cea3a23 | ||
|
|
83eb396c40 | ||
|
|
59a383e1ea | ||
|
|
fb7260792f | ||
|
|
d8a485ea7e | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 | ||
|
|
ff8d87ddee | ||
|
|
3289a25e57 | ||
|
|
df5bde7e11 | ||
|
|
b3bca04caf | ||
|
|
bf71e0bc5e | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a | ||
|
|
2a435aef66 | ||
|
|
28afb14004 | ||
|
|
8f3515572d | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 | ||
|
|
e11fb6e778 | ||
|
|
d415558915 | ||
|
|
843d6d8678 | ||
|
|
754cded24a | ||
|
|
2b6640af1e | ||
|
|
9e29c9d728 | ||
|
|
ef2569196f | ||
|
|
34cef6202b | ||
|
|
25c7003226 | ||
|
|
46e63b3612 | ||
|
|
d373389703 | ||
|
|
bc12421736 | ||
|
|
8f11ea44a7 | ||
|
|
56660b04e9 | ||
|
|
2a237c2001 | ||
|
|
77716b4ccb | ||
|
|
fb18b2de16 | ||
|
|
0de5742b04 | ||
|
|
b500a36a94 | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b | ||
|
|
765c1dc9e4 | ||
|
|
e6d9a271fc | ||
|
|
4b811dae61 | ||
|
|
6d76865e74 | ||
|
|
2bb71f41c3 | ||
|
|
cc2ab00074 | ||
|
|
8b8e8b38e5 | ||
|
|
46ea594f02 | ||
|
|
790fda1a97 | ||
|
|
89ffcf42eb | ||
|
|
876bbd715a | ||
|
|
ac0d1f52a0 | ||
|
|
d0ae0adc99 | ||
|
|
995a26660e | ||
|
|
dfd62cfb86 | ||
|
|
64dc07a8e5 | ||
|
|
ae4ae9973c | ||
|
|
36473f7de6 | ||
|
|
a14debc83e | ||
|
|
71a7473a81 | ||
|
|
5c03fb62c4 | ||
|
|
727c0cfcbf | ||
|
|
dcd2e5c34f | ||
|
|
1e276573c2 | ||
|
|
db17ff3323 | ||
|
|
b496ae8395 | ||
|
|
724f54c2c1 | ||
|
|
b6eba3347d | ||
|
|
74c22628b3 | ||
|
|
224acebb57 | ||
|
|
85c174a6ca | ||
|
|
581d242925 | ||
|
|
d9d0216e98 | ||
|
|
c52ad29b31 | ||
|
|
fcbf3f3c22 | ||
|
|
ab0002f99d | ||
|
|
f63cda22fa | ||
|
|
b60a34eba4 | ||
|
|
ed4be2c849 | ||
|
|
5e23e9c7c7 | ||
|
|
c3bfcc36b8 | ||
|
|
a33cc8c758 | ||
|
|
a01d712751 | ||
|
|
774cff9a74 | ||
|
|
e3d46b687c | ||
|
|
8636ea0ec4 | ||
|
|
ff6a66dcab | ||
|
|
2ac735657e | ||
|
|
bbab1fc891 | ||
|
|
82a50da8b1 | ||
|
|
7ddcb239c5 | ||
|
|
9e4e221970 | ||
|
|
e8b0126371 | ||
|
|
90d9a2ad1f | ||
|
|
065ef922bd | ||
|
|
7d11533490 | ||
|
|
1031a226f8 | ||
|
|
ddd98876b5 | ||
|
|
dfd41da2fd | ||
|
|
b37279ca21 | ||
|
|
13eeb07f5f | ||
|
|
1e9bac7f6e | ||
|
|
1c290767f2 | ||
|
|
9becb3f40a | ||
|
|
2c351726ae | ||
|
|
9e891d2e97 | ||
|
|
b8d07eb852 | ||
|
|
223c3dc800 | ||
|
|
afb6e89bfd | ||
|
|
9309edf4f4 | ||
|
|
d28ced8fd7 | ||
|
|
076608021c | ||
|
|
fb4f9aa58e | ||
|
|
de21f4dcd7 | ||
|
|
442bc9540e | ||
|
|
f7570712a7 | ||
|
|
2847655a1a | ||
|
|
268016d872 | ||
|
|
ac3f22c274 | ||
|
|
b36888e9cc | ||
|
|
9bb9023009 | ||
|
|
f70cb5de45 | ||
|
|
3d3586800e | ||
|
|
767de271e9 | ||
|
|
9d2c2cae37 | ||
|
|
dcccca3f7b | ||
|
|
4ed89e4ba7 | ||
|
|
99dbe4ff02 | ||
|
|
2fc0b01c18 | ||
|
|
3a86b60680 | ||
|
|
eb7c428a2d | ||
|
|
9fb9467ed1 | ||
|
|
e42036485f | ||
|
|
f9c3aff294 | ||
|
|
3503dbc7d5 | ||
|
|
b5dde6b9d8 | ||
|
|
a6b22ec1c9 | ||
|
|
bb49ebf6e5 | ||
|
|
2f5e626029 | ||
|
|
82c0a45ea0 | ||
|
|
e765051f14 | ||
|
|
f5e4df5cab | ||
|
|
1f47cc6f4e | ||
|
|
074d3af79c | ||
|
|
6593645c80 | ||
|
|
296eb82c31 | ||
|
|
7a377fc5e4 | ||
|
|
90e0c2ab15 | ||
|
|
7a3d4d1f31 | ||
|
|
e354e8697f | ||
|
|
993b578512 | ||
|
|
ed518ef19f | ||
|
|
47117a7d85 | ||
|
|
f623810903 | ||
|
|
e9ffd5752b | ||
|
|
24122b1762 | ||
|
|
081a6dacdb | ||
|
|
9fdb45be1e | ||
|
|
b946f00f1a | ||
|
|
b030f69a83 | ||
|
|
b0e1b3368e | ||
|
|
ce7b24bfb1 | ||
|
|
5c286cab8b | ||
|
|
75ca0d4fa4 | ||
|
|
8282b11fb5 | ||
|
|
45744cc789 | ||
|
|
4b6a0c433c | ||
|
|
304a14de7d | ||
|
|
c585128bbe | ||
|
|
acd92f9b06 | ||
|
|
4088b7ac3c | ||
|
|
8e8904a159 | ||
|
|
16f3490aee | ||
|
|
651084e8c0 | ||
|
|
812bb99f5c | ||
|
|
5bc79807ec | ||
|
|
8fe21d7583 | ||
|
|
412331aa61 | ||
|
|
cd1c3df89c | ||
|
|
3738373aa5 | ||
|
|
9b9006fed5 | ||
|
|
42234b8f7c | ||
|
|
39f65703e7 | ||
|
|
b7f954a904 | ||
|
|
a20815ece6 | ||
|
|
1c43bad705 | ||
|
|
18b6590d2e | ||
|
|
d62ffa7560 | ||
|
|
59e2944fb7 | ||
|
|
17942787aa | ||
|
|
5815ba24e2 | ||
|
|
5de8e9d1ae | ||
|
|
96e1e3db5e | ||
|
|
5dd36bc5ad | ||
|
|
6271b989bc | ||
|
|
57aa6bf16c | ||
|
|
40a7f4b4b1 | ||
|
|
cba0f23a9e | ||
|
|
a7ec0179fb | ||
|
|
c97c6b7836 | ||
|
|
59b0527c38 | ||
|
|
b74c7a79ab | ||
|
|
f772720d8c | ||
|
|
0763a35fbc | ||
|
|
e1c33dcd33 | ||
|
|
0a902790ca | ||
|
|
0837c8b639 | ||
|
|
5a90b6be9c | ||
|
|
42675571c9 | ||
|
|
e9f00f65ca | ||
|
|
04b95e37c5 | ||
|
|
5820e1b6ff | ||
|
|
8c904ffe34 | ||
|
|
9fa9cb4b31 | ||
|
|
24599aaeed | ||
|
|
f403b23e9a | ||
|
|
39c71a0394 | ||
|
|
d249e628ee | ||
|
|
40fcb6bdf8 | ||
|
|
d58ff5de26 | ||
|
|
e28ad18106 | ||
|
|
525411101d | ||
|
|
0f208447ed | ||
|
|
71e0573459 | ||
|
|
c63ea8d25b | ||
|
|
b9e529e0b5 | ||
|
|
0f702fcd62 | ||
|
|
13f2f9bc58 | ||
|
|
91cf202177 | ||
|
|
d21a8d597b | ||
|
|
14022f1d00 | ||
|
|
28c62f3efd | ||
|
|
268bb4bfa3 | ||
|
|
477b4f9d0e | ||
|
|
d5d88270f0 | ||
|
|
373725f96e | ||
|
|
fcb1a50ee4 | ||
|
|
ec3778bbf4 | ||
|
|
8c5b8d3b72 | ||
|
|
010ba70561 | ||
|
|
6ee057e25b | ||
|
|
551aebc604 | ||
|
|
9de85ea16e | ||
|
|
10dde452f9 | ||
|
|
116c8c5e8e | ||
|
|
f8886e874d | ||
|
|
2435a9cd58 | ||
|
|
78d53062d1 | ||
|
|
697d71d57d | ||
|
|
d74b086aaf | ||
|
|
6496aedc92 | ||
|
|
e972fad300 | ||
|
|
1bd4d6d953 | ||
|
|
e9655d43d5 | ||
|
|
f0a7ddaf80 | ||
|
|
ed6c12c709 | ||
|
|
a1b75fe17f | ||
|
|
2e5e75699e | ||
|
|
be308beacc | ||
|
|
2589176c82 | ||
|
|
adfd99bdec | ||
|
|
1683ee7b11 | ||
|
|
e6575c4149 | ||
|
|
ae7283e021 | ||
|
|
640a2cca9f | ||
|
|
12edc3455c | ||
|
|
26f631b638 | ||
|
|
981cf40561 | ||
|
|
689dda59e9 | ||
|
|
0a67f9dd39 | ||
|
|
df6bb188d4 | ||
|
|
03053d9ee0 | ||
|
|
9c4d7a83e2 | ||
|
|
7425a3c4b3 | ||
|
|
344e04b623 | ||
|
|
7b71e234e0 | ||
|
|
77f67d1766 | ||
|
|
1c2ed75937 | ||
|
|
17e6cad479 | ||
|
|
feff86638e | ||
|
|
ad28eaa86f | ||
|
|
d36bbc177d | ||
|
|
aeddb57594 | ||
|
|
f2253269dd | ||
|
|
d08cecf126 | ||
|
|
afad39d125 | ||
|
|
f97916f371 | ||
|
|
86e204439e | ||
|
|
04a931fc79 | ||
|
|
75354bbd96 | ||
|
|
6a10e97a97 | ||
|
|
1542b00db2 | ||
|
|
f79f8bac80 | ||
|
|
92f1a4aa3c | ||
|
|
11f929c397 | ||
|
|
0616338911 | ||
|
|
58427d565d | ||
|
|
9b3dbada17 | ||
|
|
4797f99cf8 | ||
|
|
50f35351a2 | ||
|
|
c7460bde16 | ||
|
|
2c110e8ce2 | ||
|
|
5707a6ee1d | ||
|
|
291411a45e | ||
|
|
87abc22f39 | ||
|
|
441582dbb8 | ||
|
|
1b1ede92ba | ||
|
|
4ec7ae33c5 | ||
|
|
317fcc659b | ||
|
|
ff7e084a33 | ||
|
|
c590beb4e3 | ||
|
|
e9ced44ac6 | ||
|
|
802cd127d1 | ||
|
|
931c56b2d0 | ||
|
|
484662b2d4 | ||
|
|
2cd04f08c1 | ||
|
|
4916dad78e | ||
|
|
d5c97faac5 | ||
|
|
531b12e192 | ||
|
|
b293b083fc | ||
|
|
b297e20f4e | ||
|
|
44be7f3ac3 | ||
|
|
ea5a100a74 | ||
|
|
6841fa17d4 | ||
|
|
5c03804bac | ||
|
|
d6ed393255 | ||
|
|
2d9139767a | ||
|
|
95fcc89074 | ||
|
|
eb59853596 | ||
|
|
a2682de421 | ||
|
|
325c0a3687 | ||
|
|
7c7fcf46c2 | ||
|
|
0c39733cbf | ||
|
|
a76413594e | ||
|
|
1100d5a6f7 | ||
|
|
9abf967700 | ||
|
|
cc83094bc6 | ||
|
|
f5bdc138f6 | ||
|
|
2d8ca48175 | ||
|
|
4ca4a1f99c | ||
|
|
5470801c4a | ||
|
|
2ad2d3e6f5 | ||
|
|
b175d6b2a3 | ||
|
|
c5c12aa738 | ||
|
|
7241400edd | ||
|
|
310fd0b187 | ||
|
|
db94743220 | ||
|
|
07aaf37fd4 | ||
|
|
65a808808f | ||
|
|
cca1aa1588 | ||
|
|
c9d4b773c9 | ||
|
|
e23f3102f4 | ||
|
|
ec89587c37 | ||
|
|
32d89806d7 | ||
|
|
2fd4e06b34 | ||
|
|
3cffdce1c1 | ||
|
|
6d2f4f4cdf | ||
|
|
865d7bd684 | ||
|
|
392d63231c | ||
|
|
7559f5ad70 | ||
|
|
605e8143e0 | ||
|
|
5b056cd337 | ||
|
|
6c350489b1 | ||
|
|
2ae63f4aa2 | ||
|
|
3d0233e3b0 | ||
|
|
64f2c3a465 | ||
|
|
0a12333448 | ||
|
|
9db54c9b19 | ||
|
|
34430e3514 | ||
|
|
99e44f2c23 | ||
|
|
7a0f2d9b30 | ||
|
|
4bf310f7ca | ||
|
|
8b9fbe701d | ||
|
|
0c5be023e4 | ||
|
|
86e87a8789 | ||
|
|
404e78a506 | ||
|
|
73563c7c25 | ||
|
|
326595b148 | ||
|
|
41a8468b08 | ||
|
|
ced2ecb6ba | ||
|
|
2d746b3a7e | ||
|
|
e6ac39de75 | ||
|
|
b76a0a6c91 | ||
|
|
9fdec3c2c8 | ||
|
|
760fe643e8 | ||
|
|
93af851dc5 | ||
|
|
fabb3e0734 | ||
|
|
9ca9a862a5 | ||
|
|
827dc9ff9f | ||
|
|
09b32ac9dd | ||
|
|
253684e280 | ||
|
|
f6d40ce841 | ||
|
|
36fb1bb7e4 | ||
|
|
4a82c1608f | ||
|
|
3efb3da007 | ||
|
|
11606fd9c6 | ||
|
|
a935db07ef | ||
|
|
98860a9549 | ||
|
|
7688742b2a | ||
|
|
b2efe4f83c | ||
|
|
f934b435fa | ||
|
|
3c121585da | ||
|
|
40acfbd2df | ||
|
|
0af61bf6ba | ||
|
|
7b2968f2ff | ||
|
|
a1c7b98f98 | ||
|
|
99ea16a969 | ||
|
|
ebe44d03a5 | ||
|
|
dcd2d50768 | ||
|
|
f11764c517 | ||
|
|
77c81b7468 | ||
|
|
7a5ccd3310 | ||
|
|
e4df6fcf8e | ||
|
|
b2be7f4e4f | ||
|
|
94beb21a43 | ||
|
|
30e05538b7 | ||
|
|
c884947ea8 | ||
|
|
61289a152d | ||
|
|
906550f9af | ||
|
|
c2aaa89b57 | ||
|
|
dde48e9414 | ||
|
|
b1608f41ad | ||
|
|
78d89e3d35 | ||
|
|
1309495218 | ||
|
|
c34a4c69e5 | ||
|
|
2f6cac0cf0 | ||
|
|
5c26df3a4f | ||
|
|
302323a64b | ||
|
|
b981fad920 | ||
|
|
8a2f2a5c2b | ||
|
|
e319735ed1 | ||
|
|
e7790490f1 | ||
|
|
a638978b75 | ||
|
|
4a08686e74 | ||
|
|
b3de2bd926 | ||
|
|
b81ec02984 | ||
|
|
de61c0c42b | ||
|
|
ecb4a1efa4 | ||
|
|
1b0093a483 | ||
|
|
06fc364ee1 | ||
|
|
094859bbc7 | ||
|
|
5e78386cdc | ||
|
|
c378afeff8 | ||
|
|
bf7002209e | ||
|
|
a3aa4bd189 | ||
|
|
5a0006f7ef | ||
|
|
9e2e73c070 | ||
|
|
c530e5d50f | ||
|
|
674720c6cd | ||
|
|
58c9e4b96d | ||
|
|
feb286379c | ||
|
|
cefe641586 | ||
|
|
664451c296 | ||
|
|
fd4ff8ca46 | ||
|
|
1bcfbdf287 | ||
|
|
4e45c1a6ab | ||
|
|
32fe80d164 | ||
|
|
6e93d42023 | ||
|
|
6f50867aa1 | ||
|
|
4fca60469d | ||
|
|
afcd824ae9 | ||
|
|
f84f279738 | ||
|
|
246624ad3c | ||
|
|
410444aead | ||
|
|
7522d3bde3 | ||
|
|
ed26b84177 | ||
|
|
ad4d12cf94 | ||
|
|
f6fd760e4e | ||
|
|
506a5260dc | ||
|
|
d4c90d696d | ||
|
|
be4d26a1b3 | ||
|
|
5c09614319 | ||
|
|
4c846332c5 | ||
|
|
a3a0cbf0f8 | ||
|
|
2c7101092a | ||
|
|
9f068356a4 | ||
|
|
f239c90628 | ||
|
|
991dd05e72 | ||
|
|
96bf54e293 | ||
|
|
5ca9b54d66 | ||
|
|
4ab5fca4ca | ||
|
|
69a4fa8215 | ||
|
|
9e04bad0a5 | ||
|
|
a574d9c936 | ||
|
|
005e13089a | ||
|
|
d9cce6402a | ||
|
|
508872e04b | ||
|
|
aced302b63 | ||
|
|
0b8dfee17b | ||
|
|
6ab246676e | ||
|
|
122c94a24a | ||
|
|
b59c6d6ab1 | ||
|
|
c9995995a4 | ||
|
|
545a9193e2 | ||
|
|
fa0205cba3 | ||
|
|
8a20bd7f54 | ||
|
|
10660f376c | ||
|
|
ae235f7155 | ||
|
|
a356cd0d0f | ||
|
|
58b932ffb8 | ||
|
|
d58af33fba | ||
|
|
a56418f8bc | ||
|
|
596e1590df | ||
|
|
70c9147c7f | ||
|
|
c0054cb56f | ||
|
|
41734dfbbf | ||
|
|
8f42d34db9 | ||
|
|
70857ce299 | ||
|
|
5e0ec38383 | ||
|
|
913d0409f6 | ||
|
|
ac0e720de1 | ||
|
|
5144d32b77 | ||
|
|
128cc21516 | ||
|
|
215ff36362 | ||
|
|
505b4d0bc3 | ||
|
|
343c0a9472 | ||
|
|
82681606d0 | ||
|
|
c91b79b6e2 | ||
|
|
5e55aa387f | ||
|
|
a21095bc9a | ||
|
|
ba03241df3 | ||
|
|
a8059dc2c0 | ||
|
|
be873bca3e | ||
|
|
e8bde958f1 | ||
|
|
95f21c1099 | ||
|
|
8cd92150b1 | ||
|
|
d0ab35931e | ||
|
|
882684a80c | ||
|
|
96efd1cef0 | ||
|
|
c8974ede6d | ||
|
|
0c637e3d5e | ||
|
|
0e2d50a620 | ||
|
|
f3b3c54859 | ||
|
|
02eca40c3b | ||
|
|
c6ee3aee9f | ||
|
|
586e0ecea9 | ||
|
|
dcd18413a2 | ||
|
|
73f296b4cf | ||
|
|
1419bf3989 | ||
|
|
dca85c402c | ||
|
|
56a3ad0f8b | ||
|
|
36f484c25a | ||
|
|
03c6685097 | ||
|
|
23afddfbf9 | ||
|
|
e3a2dfb9d0 | ||
|
|
3dd004c323 | ||
|
|
1af43dbf90 | ||
|
|
16fed12dcc | ||
|
|
29825f2f8a | ||
|
|
efcee4b863 | ||
|
|
26edcab8b4 | ||
|
|
c626892adf | ||
|
|
3c66cdf2fe | ||
|
|
db31c36213 | ||
|
|
cafe3352f1 | ||
|
|
7a39ce34fa | ||
|
|
483702df77 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde | ||
|
|
7f2a95fe14 | ||
|
|
4b3825e500 | ||
|
|
d48b42c017 | ||
|
|
fb45896588 | ||
|
|
b52518f85f | ||
|
|
3e99019af8 | ||
|
|
7d4b02689e | ||
|
|
9962f57ad0 | ||
|
|
8b538e2802 | ||
|
|
a6c57e169a | ||
|
|
6f92f0a668 | ||
|
|
35817601ff | ||
|
|
2b154db938 | ||
|
|
b9ff7aa5cd | ||
|
|
b5188e8cea | ||
|
|
992db16586 | ||
|
|
2aad749e24 | ||
|
|
aa267ebb05 | ||
|
|
1a33f25970 | ||
|
|
e8dfc42f44 | ||
|
|
21c823ecdc | ||
|
|
80498f1709 | ||
|
|
e6c5a4a4bb | ||
|
|
732b3abf99 | ||
|
|
ffbf541ff8 | ||
|
|
709f961e1c | ||
|
|
1653383573 | ||
|
|
c7ae6b9471 | ||
|
|
bbcf9ba9db | ||
|
|
3f81f9dcb4 | ||
|
|
b073fea5fb | ||
|
|
834236931e | ||
|
|
872b907372 | ||
|
|
0b8e098c10 | ||
|
|
7c6a0f869d | ||
|
|
3a43047102 | ||
|
|
041acf158a | ||
|
|
f9752d7c08 | ||
|
|
766592b83b | ||
|
|
1c3c412ce4 | ||
|
|
f9e6d1290d | ||
|
|
8ef653fcc0 | ||
|
|
fb8d66b8d3 | ||
|
|
e70b34de62 | ||
|
|
b1584fab8f | ||
|
|
718084065e | ||
|
|
57dd091e05 | ||
|
|
a1f208f1e6 | ||
|
|
581aa7279f | ||
|
|
0b29924648 | ||
|
|
49472da669 | ||
|
|
69a2eac2ff | ||
|
|
5fd632c357 | ||
|
|
bb2164c945 | ||
|
|
8c91aa5570 | ||
|
|
6db8257b1e | ||
|
|
f6e7166e79 | ||
|
|
2da8290040 | ||
|
|
4d6e8e1ca5 | ||
|
|
7e4da5b157 | ||
|
|
9acce6ddaa | ||
|
|
8054a32417 | ||
|
|
ed3958daa8 | ||
|
|
9d5c515680 | ||
|
|
0e9677965c | ||
|
|
cc29ceea80 | ||
|
|
32a17b9109 | ||
|
|
e119e18ed3 | ||
|
|
001902c881 | ||
|
|
c7a029a2bd | ||
|
|
4fac2d203b | ||
|
|
58692df0d2 | ||
|
|
68585d4638 | ||
|
|
23d2a8affc | ||
|
|
501335bc31 | ||
|
|
0cfaf7325e | ||
|
|
9c4095aaaa | ||
|
|
961df8597c | ||
|
|
139ad675b3 | ||
|
|
375afb7c33 | ||
|
|
a2330938d6 | ||
|
|
5aa517863a | ||
|
|
00cdf41899 | ||
|
|
1b98213d6d | ||
|
|
0d67424f69 | ||
|
|
1245ce984b | ||
|
|
1de1b0d6be | ||
|
|
a830cd5b1a | ||
|
|
d47059a9db | ||
|
|
10c1cae6ab | ||
|
|
87854c288b | ||
|
|
b39c629dcc | ||
|
|
b95cc59e79 | ||
|
|
7722cb6d2e | ||
|
|
c9a59a26bb | ||
|
|
e0fe4270aa | ||
|
|
0451b503a3 | ||
|
|
5ec8c9f79d | ||
|
|
0886636760 | ||
|
|
5748a995f7 | ||
|
|
dfe06261c4 | ||
|
|
29a632cb52 | ||
|
|
24c842936b | ||
|
|
8f6b21a12e | ||
|
|
dc530f7a7e | ||
|
|
79b8fd7b00 | ||
|
|
61560bef23 | ||
|
|
667c8c6166 | ||
|
|
8efbb31725 | ||
|
|
b4c74723d1 | ||
|
|
1d975ad431 | ||
|
|
8ab72e0964 | ||
|
|
7ad5d03948 | ||
|
|
6cf03d987c | ||
|
|
9b8184df7e | ||
|
|
aa5a144d04 | ||
|
|
c6d1f92ba9 | ||
|
|
07df7fb73b | ||
|
|
1e75bd223c | ||
|
|
9fae3ee0e9 | ||
|
|
a328f66bfa | ||
|
|
bb8a8444f4 | ||
|
|
3ee2e1011d | ||
|
|
e5542b7a88 | ||
|
|
76208f79de | ||
|
|
9e2324c2e5 | ||
|
|
5a08b9dd64 | ||
|
|
96d610b1f8 | ||
|
|
0c4c027e92 | ||
|
|
fefea0bdf6 | ||
|
|
6954d1b91c | ||
|
|
7e46da9f22 | ||
|
|
ab83a17d2b | ||
|
|
709cd02cf4 | ||
|
|
3e58fd6ab7 | ||
|
|
5a755ada28 | ||
|
|
b211d059d2 | ||
|
|
52681634cd | ||
|
|
35f39435f3 | ||
|
|
e7743632ec | ||
|
|
f20bbdf267 | ||
|
|
89c364a1a3 | ||
|
|
77bf5213df | ||
|
|
c2b9680a5e | ||
|
|
a973e43421 | ||
|
|
c4ff23449b | ||
|
|
320f249a31 | ||
|
|
734ab399eb | ||
|
|
da6706777b | ||
|
|
ce96ad0b61 | ||
|
|
9ef1c0c9a3 | ||
|
|
ad9bc6c1df | ||
|
|
76519303b9 | ||
|
|
448c48cd10 | ||
|
|
470f282819 | ||
|
|
3fbd02c6cf | ||
|
|
da3d8e2ecb | ||
|
|
5cbb6ea728 | ||
|
|
be526df88a | ||
|
|
95419a5e51 | ||
|
|
6b53d13c07 | ||
|
|
c9b0da63a1 | ||
|
|
33ca29c265 | ||
|
|
915083fae4 | ||
|
|
9e6ef16fb3 | ||
|
|
5608446550 | ||
|
|
50ea61f462 | ||
|
|
9709a1f5ae | ||
|
|
e63d5b240f | ||
|
|
877ab76934 | ||
|
|
032c0e5849 | ||
|
|
319ac4590f | ||
|
|
36802d707d | ||
|
|
25d20ab792 | ||
|
|
7307079d40 | ||
|
|
23861cf300 | ||
|
|
b61886b816 | ||
|
|
c0a218ca48 | ||
|
|
d4b6536a50 | ||
|
|
7934639aa1 | ||
|
|
20668e49a9 | ||
|
|
fcc94b3b2f | ||
|
|
42b510e8c8 | ||
|
|
ce841a7ef1 | ||
|
|
54dd17e7b9 | ||
|
|
32942a5f20 | ||
|
|
150b3782b9 | ||
|
|
5bfd0598e7 | ||
|
|
060a8cef00 | ||
|
|
5e3678c0af | ||
|
|
0e4f1485c8 | ||
|
|
b152462b2c | ||
|
|
e219efa22a | ||
|
|
9c070effac | ||
|
|
7a5ea7a5d8 | ||
|
|
c71e71b5ac | ||
|
|
bbf4e6bd3c | ||
|
|
fa1663c131 | ||
|
|
9b046feb1e | ||
|
|
b6d68ee28e | ||
|
|
2bece01a3b | ||
|
|
4f4691676a | ||
|
|
483a1ae371 | ||
|
|
781006f005 | ||
|
|
d8412eca9f | ||
|
|
37e17e9207 | ||
|
|
749a2076d8 | ||
|
|
f039878edd | ||
|
|
632c1417ea | ||
|
|
c00354c0b1 | ||
|
|
a002239fc4 | ||
|
|
70a13c298f | ||
|
|
8a72a2a91d | ||
|
|
842e327583 | ||
|
|
891eb02d49 | ||
|
|
8cea075a1e | ||
|
|
84fc3e96e6 | ||
|
|
2c9121553e | ||
|
|
48bf123d0c | ||
|
|
f8883d0495 | ||
|
|
8cb2b3fcfe | ||
|
|
cc3e1db22a | ||
|
|
daf8e5f53b | ||
|
|
c89798ecb1 | ||
|
|
b253d1f8ca | ||
|
|
a32701ef8d | ||
|
|
f3b773f1f0 | ||
|
|
efbab1b104 | ||
|
|
564474f927 | ||
|
|
47fcd16003 | ||
|
|
24c617d32e | ||
|
|
22e1a4cf92 | ||
|
|
79382b272c | ||
|
|
90e199d6a7 | ||
|
|
9a8a5b3935 | ||
|
|
58a8d653a8 | ||
|
|
eecb53498a | ||
|
|
5cf140b0ee | ||
|
|
85085491da | ||
|
|
6356b3ca6d | ||
|
|
978c810139 | ||
|
|
1a315235b7 | ||
|
|
bcf8b14f38 | ||
|
|
fe69e96942 | ||
|
|
e9d40e4481 | ||
|
|
ed9f561dc3 | ||
|
|
7de054fa49 | ||
|
|
fe86836b43 | ||
|
|
973e62373e | ||
|
|
dcdb9ac923 | ||
|
|
46347e2bd2 |
No files matched your search
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: btca-cli
|
||||
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
|
||||
---
|
||||
|
||||
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
|
||||
|
||||
For example, assuming you have a resource named `codex`, you can ask questions like:
|
||||
|
||||
```bash
|
||||
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
|
||||
```
|
||||
|
||||
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
|
||||
|
||||
New resources can be created if the ones you need do not yet exist.
|
||||
|
||||
```bash
|
||||
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
|
||||
```
|
||||
@@ -1,3 +0,0 @@
|
||||
interface:
|
||||
display_name: "BTCA CLI"
|
||||
short_description: "Help with BTCA CLI setup and usage workflows"
|
||||
@@ -0,0 +1 @@
|
||||
plans/
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Cursor Cloud specific instructions
|
||||
|
||||
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
|
||||
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
|
||||
|
||||
## Toolchain
|
||||
|
||||
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
|
||||
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
|
||||
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
|
||||
|
||||
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
|
||||
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
|
||||
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
|
||||
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
|
||||
`vp check --fix` before committing.
|
||||
|
||||
## Running the web app
|
||||
|
||||
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
|
||||
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
|
||||
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
|
||||
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
|
||||
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
|
||||
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
|
||||
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
|
||||
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
|
||||
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
|
||||
Without one installed the UI loads but no agent can run. Claude Code
|
||||
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
|
||||
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
|
||||
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
|
||||
server to pick up a newly installed provider CLI immediately.
|
||||
|
||||
## Android native builds (apps/mobile)
|
||||
|
||||
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
|
||||
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
|
||||
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
|
||||
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
|
||||
Gradle auto-downloads any additional pinned SDK packages on demand.
|
||||
|
||||
- Generate the native project first: from `apps/mobile`,
|
||||
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
|
||||
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
|
||||
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
|
||||
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
|
||||
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
|
||||
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
|
||||
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
|
||||
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
|
||||
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
|
||||
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
|
||||
Android Studio bundles is what is installed.
|
||||
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
|
||||
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
|
||||
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
|
||||
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
|
||||
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
|
||||
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
|
||||
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
|
||||
scope for environment setup.
|
||||
|
||||
## Known flaky tests (unrelated to setup)
|
||||
|
||||
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
|
||||
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24.13.1"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": ["oxc.oxc-vscode"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Optional: T3 Connect source builds
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
|
||||
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
# returns a different RP ID or when multiple domains must be entitled.
|
||||
# T3CODE_APPLE_TEAM_ID=ABC1234567
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
|
||||
@@ -0,0 +1,2 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,117 @@
|
||||
name: Bug report
|
||||
description: Report broken behavior, regressions, crashes, or reliability issues.
|
||||
title: "[Bug]: "
|
||||
labels:
|
||||
- bug
|
||||
- needs-triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for broken behavior, regressions, crashes, or reliability problems.
|
||||
Search existing issues first and keep the report focused on one problem.
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before submitting
|
||||
options:
|
||||
- label: I searched existing issues and did not find a duplicate.
|
||||
required: true
|
||||
- label: I included enough detail to reproduce or investigate the problem.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: Which part of the project is affected?
|
||||
options:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Provide a minimal, deterministic repro.
|
||||
placeholder: |
|
||||
1. Start the app with ...
|
||||
2. Open ...
|
||||
3. Disconnect the network
|
||||
4. Reconnect and send another prompt
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
placeholder: The thread should resume normally and accept the new message.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual behavior
|
||||
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: impact
|
||||
attributes:
|
||||
label: Impact
|
||||
description: How bad is this in practice?
|
||||
options:
|
||||
- Blocks work completely
|
||||
- Major degradation or frequent failure
|
||||
- Minor bug or occasional failure
|
||||
- Cosmetic issue
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version or commit
|
||||
description: Release version, commit SHA, or branch name if known.
|
||||
placeholder: main @ abc1234
|
||||
|
||||
- type: input
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
|
||||
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Logs or stack traces
|
||||
description: Paste the most relevant output only. Redact secrets.
|
||||
render: shell
|
||||
|
||||
- type: upload
|
||||
id: attachments
|
||||
attributes:
|
||||
label: Screenshots, recordings, or supporting files
|
||||
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
|
||||
validations:
|
||||
required: false
|
||||
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
|
||||
|
||||
- type: textarea
|
||||
id: workaround
|
||||
attributes:
|
||||
label: Workaround
|
||||
description: If you found a temporary workaround, include it.
|
||||
placeholder: Restarting the provider session clears the stuck state.
|
||||
@@ -0,0 +1,101 @@
|
||||
name: Feature request
|
||||
description: Propose a scoped improvement or new capability.
|
||||
title: "[Feature]: "
|
||||
labels:
|
||||
- enhancement
|
||||
- needs-triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for new capabilities or meaningful improvements to existing behavior.
|
||||
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before submitting
|
||||
options:
|
||||
- label: I searched existing issues and did not find a duplicate.
|
||||
required: true
|
||||
- label: I am describing a concrete problem or use case, not just a vague idea.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: Which part of the project would this change affect?
|
||||
options:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or use case
|
||||
description: What are you trying to do? What is hard, slow, or impossible today?
|
||||
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: Describe the behavior, API, or UX you want.
|
||||
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: value
|
||||
attributes:
|
||||
label: Why this matters
|
||||
description: Who benefits, and what outcome does this unlock?
|
||||
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Smallest useful scope
|
||||
description: What is the narrowest version of this request that would still solve your problem?
|
||||
placeholder: A first pass only needs to support restoring the active session for the current thread.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives considered
|
||||
description: Workarounds, prior art, or other approaches you considered.
|
||||
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
|
||||
|
||||
- type: textarea
|
||||
id: tradeoffs
|
||||
attributes:
|
||||
label: Risks or tradeoffs
|
||||
description: What costs, complexity, or edge cases should be considered?
|
||||
placeholder: This may require careful handling when the underlying provider session has already exited.
|
||||
|
||||
- type: textarea
|
||||
id: references
|
||||
attributes:
|
||||
label: Examples or references
|
||||
description: Links, screenshots, mockups, or comparable tools.
|
||||
|
||||
- type: checkboxes
|
||||
id: contribution
|
||||
attributes:
|
||||
label: Contribution
|
||||
options:
|
||||
- label: I would be open to helping implement this.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Trust list for this repository.
|
||||
#
|
||||
# External contributors listed here are treated as trusted by the vouch
|
||||
# workflow. Collaborators with write access are automatically trusted and
|
||||
# do not need to be duplicated in this file.
|
||||
#
|
||||
# Syntax:
|
||||
# github:username
|
||||
# -github:username reason for denouncement
|
||||
#
|
||||
# Keep entries sorted alphabetically.
|
||||
github:adityavardhansharma
|
||||
github:binbandit
|
||||
github:chuks-qua
|
||||
github:cursoragent
|
||||
github:gbarros-dev
|
||||
github:github-actions[bot]
|
||||
github:hwanseoc
|
||||
github:jamesx0416
|
||||
github:jasonLaster
|
||||
github:JoeEverest
|
||||
github:maria-rcks
|
||||
github:nmggithub
|
||||
github:Noojuno
|
||||
github:notkainoa
|
||||
github:PatrickBauer
|
||||
github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
@@ -0,0 +1,33 @@
|
||||
<!--
|
||||
⚠️ READ BEFORE OPENING ⚠️
|
||||
|
||||
We are not actively accepting contributions right now.
|
||||
|
||||
You can still open a PR, but please do so knowing there is a high chance
|
||||
we may close it without merging it, or never review it.
|
||||
|
||||
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
|
||||
- New features will most likely just annoy us.
|
||||
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
|
||||
-->
|
||||
|
||||
## What Changed
|
||||
|
||||
<!-- Describe the change clearly and keep scope tight. -->
|
||||
|
||||
## Why
|
||||
|
||||
<!-- Explain the problem being solved and why this approach is the right one. -->
|
||||
|
||||
## UI Changes
|
||||
|
||||
<!-- If this PR changes UI, include clear before/after screenshots.
|
||||
If the change involves motion or interaction, include a short video.
|
||||
Delete this section if not applicable. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] This PR is small and focused
|
||||
- [ ] I explained what changed and why
|
||||
- [ ] I included before/after screenshots for any UI changes
|
||||
- [ ] I included a video for animation/interaction changes
|
||||
+79
-28
@@ -7,44 +7,95 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
runs-on: ubuntu-latest
|
||||
check:
|
||||
name: Check
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
.turbo
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
- name: Check
|
||||
run: vp check
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
run: vp run build:desktop
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
test:
|
||||
name: Test
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Install mobile native static analysis tools
|
||||
run: brew bundle install --file apps/mobile/Brewfile
|
||||
|
||||
- name: Lint mobile native sources
|
||||
run: vp run lint:mobile
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -0,0 +1,80 @@
|
||||
name: Deploy T3 Connect relay
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: none
|
||||
statuses: write
|
||||
|
||||
concurrency:
|
||||
group: relay-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy_relay:
|
||||
name: Deploy production relay
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
environment:
|
||||
name: production
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
|
||||
AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
|
||||
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
|
||||
APNS_TEAM_ID: ${{ vars.APNS_TEAM_ID }}
|
||||
APNS_KEY_ID: ${{ vars.APNS_KEY_ID }}
|
||||
APNS_BUNDLE_ID: ${{ vars.APNS_BUNDLE_ID }}
|
||||
ALCHEMY_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Deploy production relay stage
|
||||
id: deploy
|
||||
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
|
||||
PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
|
||||
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
|
||||
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
|
||||
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
|
||||
|
||||
- name: Publish relay deploy commit status
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const result = "${{ steps.deploy.outputs.result }}";
|
||||
const changed = "${{ steps.deploy.outputs.changed }}" === "true";
|
||||
const description = changed
|
||||
? "Relay production deploy applied infrastructure changes."
|
||||
: result === "noop"
|
||||
? "Relay production deploy was a no-op."
|
||||
: `Relay production deploy completed with result: ${result}.`;
|
||||
|
||||
await github.rest.repos.createCommitStatus({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
sha: context.sha,
|
||||
state: "success",
|
||||
context: "Relay deploy / production",
|
||||
description,
|
||||
target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Issue Labels
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- .github/ISSUE_TEMPLATE/**
|
||||
- .github/workflows/issue-labels.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Sync issue labels
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Ensure managed issue labels exist
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "bug",
|
||||
color: "d73a4a",
|
||||
description: "Something is broken or behaving incorrectly.",
|
||||
},
|
||||
{
|
||||
name: "enhancement",
|
||||
color: "a2eeef",
|
||||
description: "Requested improvement or new capability.",
|
||||
},
|
||||
{
|
||||
name: "needs-triage",
|
||||
color: "fbca04",
|
||||
description: "Issue needs maintainer review and initial categorization.",
|
||||
},
|
||||
];
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
env:
|
||||
APP_VARIANT: preview
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
MOBILE_VERSION_POLICY: fingerprint
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS preview."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull preview environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull preview --non-interactive
|
||||
|
||||
- name: Deploy with fingerprint check
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
with:
|
||||
profile: preview:dev
|
||||
branch: pr-${{ github.event.pull_request.number }}
|
||||
platform: all
|
||||
environment: preview
|
||||
working-directory: apps/mobile
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,113 @@
|
||||
name: Mobile EAS Production
|
||||
|
||||
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
|
||||
# Under the fingerprint runtime-version policy the fingerprint must be computed
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "build (+ auto-submit to TestFlight) or update (OTA)"
|
||||
required: true
|
||||
type: choice
|
||||
default: build
|
||||
options:
|
||||
- build
|
||||
- update
|
||||
platform:
|
||||
description: "Target platform"
|
||||
required: true
|
||||
type: choice
|
||||
default: ios
|
||||
options:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull production environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
@@ -0,0 +1,295 @@
|
||||
name: PR Size
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
prepare-config:
|
||||
name: Prepare PR size config
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
labels_json: ${{ steps.config.outputs.labels_json }}
|
||||
steps:
|
||||
- id: config
|
||||
name: Build PR size label config
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
result-encoding: string
|
||||
script: |
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "size:XS",
|
||||
color: "0e8a16",
|
||||
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:S",
|
||||
color: "5ebd3e",
|
||||
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:M",
|
||||
color: "fbca04",
|
||||
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:L",
|
||||
color: "fe7d37",
|
||||
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XL",
|
||||
color: "d93f0b",
|
||||
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XXL",
|
||||
color: "b60205",
|
||||
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
];
|
||||
|
||||
core.setOutput("labels_json", JSON.stringify(managedLabels));
|
||||
sync-label-definitions:
|
||||
name: Sync PR size label definitions
|
||||
needs: prepare-config
|
||||
if: github.event_name != 'pull_request_target'
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- name: Ensure PR size labels exist
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
label:
|
||||
name: Label PR size
|
||||
needs: prepare-config
|
||||
if: github.event_name == 'pull_request_target'
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: write
|
||||
concurrency:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# This pull_request_target job may fetch untrusted PR commits only as passive
|
||||
# git data. Do not add dependency installs, build/test scripts, or cache
|
||||
# actions here; use pull_request plus workflow_run for that pattern instead.
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Sync PR size label
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const baseSha = context.payload.pull_request.base.sha;
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||
const testExcludePathspecs = [
|
||||
":(glob,exclude)**/__tests__/**",
|
||||
":(glob,exclude)**/test/**",
|
||||
":(glob,exclude)**/tests/**",
|
||||
":(glob,exclude)apps/server/integration/**",
|
||||
":(glob,exclude)**/*.test.*",
|
||||
":(glob,exclude)**/*.spec.*",
|
||||
":(glob,exclude)**/*.browser.*",
|
||||
":(glob,exclude)**/*.integration.*",
|
||||
];
|
||||
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
return "size:XS";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 30) {
|
||||
return "size:S";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 100) {
|
||||
return "size:M";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 500) {
|
||||
return "size:L";
|
||||
}
|
||||
|
||||
if (totalChangedLines < 1000) {
|
||||
return "size:XL";
|
||||
}
|
||||
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
{
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
core.warning(
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
);
|
||||
}
|
||||
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
for (const label of currentLabels) {
|
||||
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: label.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentLabels.some((label) => label.name === nextLabelName)) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [nextLabelName],
|
||||
});
|
||||
}
|
||||
|
||||
const classification =
|
||||
nonTestChangedLines === 0
|
||||
? testChangedLines > 0
|
||||
? "test-only PR"
|
||||
: "no line changes"
|
||||
: testChangedLines > 0
|
||||
? "test lines excluded"
|
||||
: "all non-test changes";
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
|
||||
);
|
||||
@@ -0,0 +1,199 @@
|
||||
name: PR Vouch
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- .github/VOUCHED.td
|
||||
- .github/workflows/pr-vouch.yml
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
collect-targets:
|
||||
name: Collect PR targets
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
targets: ${{ steps.collect.outputs.targets }}
|
||||
steps:
|
||||
- id: collect
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
if (context.eventName === "pull_request_target") {
|
||||
const pr = context.payload.pull_request;
|
||||
core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }]));
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.eventName === "issue_comment") {
|
||||
const issue = context.payload.issue;
|
||||
const body = context.payload.comment?.body ?? "";
|
||||
if (!issue?.pull_request || !body.includes("/recheck-vouch")) {
|
||||
core.setOutput("targets", "[]");
|
||||
return;
|
||||
}
|
||||
|
||||
core.setOutput(
|
||||
"targets",
|
||||
JSON.stringify([{ number: issue.number, user: issue.user.login }]),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const pulls = await github.paginate(github.rest.pulls.list, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
state: "open",
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const targets = pulls.map((pull) => ({
|
||||
number: pull.number,
|
||||
user: pull.user.login,
|
||||
}));
|
||||
core.setOutput("targets", JSON.stringify(targets));
|
||||
|
||||
label:
|
||||
name: Label PR ${{ matrix.target.number }}
|
||||
needs: collect-targets
|
||||
if: ${{ needs.collect-targets.outputs.targets != '[]' }}
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: pr-vouch-${{ matrix.target.number }}
|
||||
cancel-in-progress: true
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target: ${{ fromJson(needs.collect-targets.outputs.targets) }}
|
||||
steps:
|
||||
- id: vouch
|
||||
name: Check PR author trust
|
||||
uses: mitchellh/vouch/action/check-user@v1
|
||||
with:
|
||||
user: ${{ matrix.target.user }}
|
||||
allow-fail: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Sync PR labels
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ matrix.target.number }}
|
||||
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
|
||||
with:
|
||||
script: |
|
||||
const issueNumber = Number(process.env.PR_NUMBER);
|
||||
const status = process.env.VOUCH_STATUS;
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "vouch:trusted",
|
||||
color: "1f883d",
|
||||
description: "PR author is trusted by repo permissions or the VOUCHED list.",
|
||||
},
|
||||
{
|
||||
name: "vouch:unvouched",
|
||||
color: "fbca04",
|
||||
description: "PR author is not yet trusted in the VOUCHED list.",
|
||||
},
|
||||
{
|
||||
name: "vouch:denounced",
|
||||
color: "d1242f",
|
||||
description: "PR author is explicitly blocked by the VOUCHED list.",
|
||||
},
|
||||
];
|
||||
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const nextLabelName =
|
||||
status === "denounced"
|
||||
? "vouch:denounced"
|
||||
: ["bot", "collaborator", "vouched"].includes(status)
|
||||
? "vouch:trusted"
|
||||
: "vouch:unvouched";
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
for (const label of currentLabels) {
|
||||
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: label.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentLabels.some((label) => label.name === nextLabelName)) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [nextLabelName],
|
||||
});
|
||||
}
|
||||
|
||||
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
|
||||
File diff suppressed because it is too large.
Load diff
+22
@@ -5,8 +5,30 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
infra/*/dist
|
||||
.astro
|
||||
packages/*/dist
|
||||
.env
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
.vercel
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo"
|
||||
],
|
||||
"experimentalSortPackageJson": {}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
"suspicious": "warn",
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off"
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
# Plan: Centralize Model Normalization in Contracts
|
||||
|
||||
## Summary
|
||||
|
||||
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Removes duplicated logic between:
|
||||
- `apps/desktop/src/codexAppServerManager.ts`
|
||||
- `apps/renderer/src/model-logic.ts`
|
||||
- Prevents behavior drift when model aliases/defaults are updated.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add shared model utilities to contracts.
|
||||
- Update desktop and renderer to consume shared utilities.
|
||||
- Keep renderer-specific display options in renderer.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add `packages/contracts/src/model.ts` with:
|
||||
- Canonical model list
|
||||
- Alias map
|
||||
@@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and
|
||||
- Keep renderer tests focused on renderer-only behavior.
|
||||
|
||||
## Risks
|
||||
|
||||
- Desktop/renderer may currently rely on slightly different fallback behavior.
|
||||
- Import graph must avoid bundling issues for Electron main/preload.
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- `bun run typecheck`
|
||||
- Manual check that model selection and session start still send expected model slug.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- No duplicated alias/default map in desktop and renderer.
|
||||
- Shared model utilities are contract-tested.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Strengthen Typed IPC Boundaries in Main Process
|
||||
|
||||
## Summary
|
||||
|
||||
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
|
||||
- Casts can hide contract breakages until runtime.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop main process IPC registration.
|
||||
- Optional shared helper for handler registration.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
|
||||
- Parse payload(s) with Zod schemas
|
||||
- Standardize typed handler signatures
|
||||
@@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ
|
||||
4. Add tests for handler parsing failure paths (invalid payloads).
|
||||
|
||||
## Risks
|
||||
|
||||
- Refactor can subtly change IPC error shape/messages.
|
||||
- Helper abstraction should stay simple and not obscure control flow.
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- `bun run typecheck`
|
||||
- Manual invalid payload check from renderer/devtools to confirm fast failure.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- No provider handler uses `payload as Parameters<...>`.
|
||||
- All IPC entrypoints parse unknown payloads at boundary.
|
||||
@@ -1,9 +1,11 @@
|
||||
# Plan: Decompose CodexAppServerManager
|
||||
|
||||
## Summary
|
||||
|
||||
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
|
||||
- Process lifecycle
|
||||
- JSON-RPC parsing/routing
|
||||
@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
|
||||
- This increases regression risk and slows changes.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop provider internals only.
|
||||
- Keep external behavior/API stable.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Extract modules:
|
||||
- `codex/processLifecycle.ts`
|
||||
- `codex/jsonrpcRouter.ts`
|
||||
@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
|
||||
- Session state transitions
|
||||
|
||||
## Risks
|
||||
|
||||
- Reordering event handling can change behavior.
|
||||
- Must preserve pending request timeout/cancellation semantics.
|
||||
|
||||
## Validation
|
||||
|
||||
- Existing tests pass.
|
||||
- Add module-level tests for parsing and transition logic.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Main manager file materially smaller and orchestration-focused.
|
||||
- Core protocol/state logic covered by focused tests.
|
||||
@@ -1,9 +1,11 @@
|
||||
# Plan: Split ChatView into Smaller UI/Logic Units
|
||||
|
||||
## Summary
|
||||
|
||||
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
|
||||
- Session orchestration
|
||||
- Send/interrupt actions
|
||||
@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
|
||||
- Hard to test and maintain as one component.
|
||||
|
||||
## Scope
|
||||
|
||||
- Renderer component boundaries and hooks.
|
||||
- Keep visual behavior unchanged.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
|
||||
- `ensureSession`
|
||||
- `sendTurn`
|
||||
@@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
|
||||
4. Add focused tests for hook behavior (error handling, session reuse).
|
||||
|
||||
## Risks
|
||||
|
||||
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- Manual smoke: send, stream, interrupt, model switch.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- `ChatView.tsx` significantly reduced and easier to scan.
|
||||
- Session logic isolated from rendering.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Move Renderer Persisted-State Validation to Zod
|
||||
|
||||
## Summary
|
||||
|
||||
Use explicit Zod schemas for localStorage state parsing and migration.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/renderer/src/store.ts` has large manual sanitize functions.
|
||||
- Manual type guards are verbose and easier to get wrong during schema evolution.
|
||||
|
||||
## Scope
|
||||
|
||||
- Renderer state hydration/persistence path.
|
||||
- No backend/protocol changes.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
|
||||
- Persisted payload versions (`v1`, `v2`)
|
||||
- Thread/message/project schemas
|
||||
@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.
|
||||
- Unknown thread/project references filtered
|
||||
|
||||
## Risks
|
||||
|
||||
- Overly strict schemas could drop valid historical data unexpectedly.
|
||||
|
||||
## Validation
|
||||
|
||||
- Unit tests for migration/hydration.
|
||||
- Manual reload test with existing localStorage data.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Store hydration logic is schema-driven.
|
||||
- Migration behavior is tested and documented.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Add Provider Log Stream Lifecycle Management
|
||||
|
||||
## Summary
|
||||
|
||||
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
|
||||
- Stream lifecycle is not explicit on shutdown.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop provider logging behavior.
|
||||
- App shutdown integration.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add explicit `dispose()` on `ProviderManager`:
|
||||
- Remove event listeners
|
||||
- End/close log stream
|
||||
@@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and
|
||||
4. Optional: per-session log files under `.logs/providers/`.
|
||||
|
||||
## Risks
|
||||
|
||||
- Improper close sequencing may lose final log lines.
|
||||
|
||||
## Validation
|
||||
|
||||
- Manual run/quit cycle to ensure no open handle warnings.
|
||||
- Confirm logs flush on quit and file descriptors are not leaked.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- ProviderManager owns complete log stream lifecycle.
|
||||
- Shutdown path explicitly disposes provider resources.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Add CI Workflow for Core Quality Gates
|
||||
|
||||
## Summary
|
||||
|
||||
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Repository currently has no CI workflow files.
|
||||
- Quality checks are only local/manual.
|
||||
|
||||
## Scope
|
||||
|
||||
- `.github/workflows/ci.yml`
|
||||
- Bun + Turbo setup in CI.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add `ci.yml` with jobs:
|
||||
- Setup Bun and Node environment
|
||||
- Install deps
|
||||
@@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes
|
||||
3. Configure caching for Bun/Turbo as appropriate.
|
||||
|
||||
## Risks
|
||||
|
||||
- Smoke test may be flaky in headless CI environments.
|
||||
- CI runtime can grow if caching is misconfigured.
|
||||
|
||||
## Validation
|
||||
|
||||
- Verify workflow runs on a branch PR.
|
||||
- Ensure failures surface clearly by job name.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- CI blocks regressions in lint/typecheck/test.
|
||||
- Workflow docs added to README.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Add Pre-Commit Formatting/Lint Hooks
|
||||
|
||||
## Summary
|
||||
|
||||
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Current lint failures include formatting-only issues.
|
||||
- Shift-left feedback reduces noisy CI failures and cleanup churn.
|
||||
|
||||
## Scope
|
||||
|
||||
- Root tooling config and package scripts.
|
||||
- No runtime code changes.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
|
||||
2. Configure staged-file tasks:
|
||||
- `biome format --write`
|
||||
@@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor
|
||||
4. Keep checks fast to avoid developer friction.
|
||||
|
||||
## Risks
|
||||
|
||||
- Slow hooks can frustrate contributors and be bypassed.
|
||||
- Need to ensure compatibility with Bun workspace setup.
|
||||
|
||||
## Validation
|
||||
|
||||
- Create sample staged changes and verify hook behavior.
|
||||
- Confirm formatting fixes are applied automatically.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Pre-commit hook installed and documented.
|
||||
- Formatting-only lint failures drop significantly.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Expand Event/State Transition Test Coverage
|
||||
|
||||
## Summary
|
||||
|
||||
Add focused tests for renderer event handling and session evolution logic.
|
||||
|
||||
## Motivation
|
||||
|
||||
- Core behavior is event-driven and stateful.
|
||||
- Existing renderer tests cover only a subset of timeline/model behavior.
|
||||
|
||||
## Scope
|
||||
|
||||
- `apps/renderer/src/session-logic.test.ts`
|
||||
- Optional reducer tests for `apps/renderer/src/store.ts`.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Add tests for `evolveSession`:
|
||||
- `thread/started`
|
||||
- `turn/started`
|
||||
@@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic.
|
||||
3. Add reducer integration tests for `APPLY_EVENT`.
|
||||
|
||||
## Risks
|
||||
|
||||
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
|
||||
|
||||
## Validation
|
||||
|
||||
- `bun run test`
|
||||
- Ensure new tests remain deterministic and fast.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- High-risk event transitions are covered by unit tests.
|
||||
- Regressions in stream assembly/session status are caught quickly.
|
||||
@@ -1,17 +1,21 @@
|
||||
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
|
||||
|
||||
## Summary
|
||||
|
||||
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
|
||||
|
||||
## Motivation
|
||||
|
||||
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
|
||||
- New execution backends/providers will multiply complexity.
|
||||
|
||||
## Scope
|
||||
|
||||
- Desktop process execution internals.
|
||||
- Preserve public `ProcessManager` API.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
1. Introduce internal interface (e.g. `RuntimeSession`):
|
||||
- `write(data)`
|
||||
- `kill()`
|
||||
@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
|
||||
5. Add tests for both implementations.
|
||||
|
||||
## Risks
|
||||
|
||||
- PTY behavior differs by platform; abstraction must not hide required differences.
|
||||
|
||||
## Validation
|
||||
|
||||
- Existing `processManager.test.ts` passes.
|
||||
- Add PTY-path tests where feasible.
|
||||
|
||||
## Done Criteria
|
||||
|
||||
- Manager no longer branches per backend in `write/kill/killAll`.
|
||||
- Session backends are independently testable.
|
||||
@@ -0,0 +1,40 @@
|
||||
PR 1: Service contracts + error taxonomy
|
||||
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
|
||||
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
|
||||
No behavior change yet, just interfaces and compile-time wiring points.
|
||||
PR 2: CheckpointStore Effect adapter
|
||||
Wrap current filesystemCheckpointStore behind CheckpointStoreLive (adapter).
|
||||
Map all thrown/Promise errors to tagged errors.
|
||||
Add service tests proving parity for isGitRepository, capture, restore, diff, prune.
|
||||
PR 3: CodexService Effect adapter
|
||||
Wrap current CodexAppServerManager behind CodexServiceLive (adapter).
|
||||
Convert public API to Effect return types with typed errors.
|
||||
Preserve existing EventEmitter internally for now, but expose Effect-friendly subscribe API.
|
||||
PR 4: ProviderService Effect adapter
|
||||
Wrap current ProviderManager behind ProviderServiceLive (adapter).
|
||||
Provider methods become Effect methods with typed errors.
|
||||
Route emitted provider events through an Effect PubSub surface.
|
||||
PR 5: wsServer migration to Effect services
|
||||
Stop instantiating provider/codex classes directly in wsServer.
|
||||
Resolve ProviderService (and related services) from one runtime/layer graph.
|
||||
Keep WS contract behavior identical.
|
||||
PR 6: Native CheckpointStore implementation
|
||||
Refactor checkpoint internals from Promise/throws to native Effect.
|
||||
Replace ad-hoc locking with Effect concurrency primitive (keyed lock/semaphore/queue).
|
||||
Keep adapter tests plus new failure-path tests.
|
||||
PR 7: Codex transport/RPC core as native Effect
|
||||
Split codex into scoped process layer + RPC request/response layer + session registry.
|
||||
Replace timeout/pending maps with Deferred + Effect timeout/finalizer semantics.
|
||||
Keep protocol behavior and ordering guarantees.
|
||||
PR 8: Codex protocol decoding hardening
|
||||
Replace ad-hoc unknown parsing with runtime schema decoding for inbound/outbound protocol shapes.
|
||||
Map decode failures to typed tagged errors (with root cause).
|
||||
Add regression tests for malformed/partial protocol messages.
|
||||
PR 9: Native ProviderService orchestration
|
||||
Rebuild provider logic in Effect using CodexService + CheckpointStore dependencies.
|
||||
Move event fanout, checkpoint capture/revert orchestration, thread-log routing to Effect state/services.
|
||||
Remove throw-based flow entirely from provider path.
|
||||
PR 10: Cleanup + deprecation removal
|
||||
Remove legacy class implementations/adapters once parity is proven.
|
||||
Finalize layer composition and startup graph docs.
|
||||
Add architecture notes for service boundaries and error model.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Effect Migration Plan (From Current State)
|
||||
|
||||
Current status summary:
|
||||
|
||||
- Service contracts, typed errors, and most checkpoint/persistence services exist.
|
||||
- `ProviderServiceLive` is already native orchestration (not a thin adapter).
|
||||
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
|
||||
- Checkpoint flow now avoids snapshot re-sync and is write-time driven.
|
||||
|
||||
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
|
||||
|
||||
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
|
||||
- Resolve `ProviderService` from runtime in `wsServer`.
|
||||
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
|
||||
- Forward provider events by subscribing to `ProviderService.subscribeToEvents`.
|
||||
- Keep WS method/push payloads identical.
|
||||
|
||||
## PR 2: Runtime Composition + Startup Ownership
|
||||
|
||||
- Create/centralize `AppLive` composition for server startup.
|
||||
- Ensure outer runtime provides Node/platform services once.
|
||||
- Ensure migrations run at startup via scoped/layer startup path.
|
||||
- Remove ad-hoc service initialization in request-time paths.
|
||||
|
||||
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
|
||||
|
||||
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
|
||||
- Remove per-session lock/cwd map leaks.
|
||||
- Keep strict invariant model:
|
||||
- root checkpoint created at session initialization before agent modifications
|
||||
- each completed turn captures filesystem checkpoint and persists metadata
|
||||
- no after-the-fact metadata rebuild/sync
|
||||
- Add tests for lifecycle cleanup and invariant-failure surfaces.
|
||||
|
||||
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
|
||||
|
||||
- Keep `ProviderService` as the public event surface.
|
||||
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.
|
||||
- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
|
||||
- Add tests for ordering and subscriber isolation under load.
|
||||
|
||||
## PR 5: Codex Runtime Split (Scoped Effect Core)
|
||||
|
||||
- Extract `CodexAppServerManager` responsibilities into Effect-native layers:
|
||||
- scoped process lifecycle
|
||||
- RPC request/response + pending map via `Deferred`
|
||||
- session registry/state
|
||||
- Keep `CodexAdapter` contract stable while swapping internals.
|
||||
- Preserve protocol behavior and timeout semantics.
|
||||
|
||||
## PR 6: Codex Protocol Decode Hardening
|
||||
|
||||
- Replace ad-hoc unknown parsing with runtime schema decode.
|
||||
- Map decode failures to typed tagged errors with `cause` retained.
|
||||
- Add regression tests for malformed/partial protocol frames.
|
||||
|
||||
## PR 7: Remove Legacy Provider Stack
|
||||
|
||||
- Remove `ProviderManager` + legacy checkpoint integration from runtime path.
|
||||
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
|
||||
- Update tests to assert only Effect service path is used.
|
||||
|
||||
## PR 8: Final Cleanup + Docs
|
||||
|
||||
- Update architecture docs with final layer graph and service boundaries.
|
||||
- Document error model and recovery semantics.
|
||||
- Trim dead compatibility code and stale plan references.
|
||||
@@ -0,0 +1,123 @@
|
||||
# ProviderService Integration Test Plan
|
||||
|
||||
Goal:
|
||||
|
||||
- Validate end-to-end `ProviderService` behavior with real layers:
|
||||
- `ProviderServiceLive`
|
||||
- `CheckpointServiceLive`
|
||||
- `CheckpointStoreLive`
|
||||
- `CheckpointRepositoryLive` (sqlite in-memory)
|
||||
- `ProviderSessionDirectoryLive`
|
||||
- Only fake the adapter event source (deterministic Codex-like stream).
|
||||
- Avoid mocking checkpointing/persistence orchestration logic.
|
||||
|
||||
## Test Harness
|
||||
|
||||
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
|
||||
|
||||
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
- Internal state:
|
||||
- session registry (session + cwd + threadId)
|
||||
- thread snapshot store (`threadId`, `turns`)
|
||||
- event subscribers
|
||||
- Behavior:
|
||||
- `startSession`: creates session with threadId.
|
||||
- `sendTurn`: appends a deterministic turn snapshot and emits ordered events:
|
||||
- `turn/started`
|
||||
- `item/started` / `item/completed` (tool + approval variants depending on scenario)
|
||||
- `item/agentMessage/delta` chunks
|
||||
- `turn/completed`
|
||||
- optional "mutator" callback per turn to change workspace files before completion.
|
||||
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
|
||||
|
||||
Use real git-backed temporary workspaces in integration tests:
|
||||
|
||||
- initialize repo with baseline commit
|
||||
- run provider turn in workspace
|
||||
- assert checkpoint diffs against real git refs
|
||||
|
||||
## Core Integration Specs
|
||||
|
||||
1. `startSession` initializes checkpoint root exactly once
|
||||
|
||||
- Arrange:
|
||||
- start provider session in git repo.
|
||||
- Assert:
|
||||
- `provider_checkpoints` contains root row (turn 0).
|
||||
- checkpoint ref exists in git.
|
||||
- second `startSession` for new session creates a new independent root.
|
||||
|
||||
2. Turn without filesystem change
|
||||
|
||||
- Arrange:
|
||||
- emit normal turn events, no file mutation.
|
||||
- Assert:
|
||||
- provider subscribers receive:
|
||||
- `turn/started`
|
||||
- `turn/completed`
|
||||
- synthetic `checkpoint/captured`
|
||||
- `listCheckpoints` returns root + turn 1.
|
||||
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
|
||||
|
||||
3. Turn with filesystem change
|
||||
|
||||
- Arrange:
|
||||
- mutate `README.md` during turn.
|
||||
- Assert:
|
||||
- `listCheckpoints` returns root + turn 1.
|
||||
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
|
||||
- persisted checkpoint metadata includes non-empty `checkpointRef`.
|
||||
|
||||
4. Multi-turn sequencing and checkpoint monotonicity
|
||||
|
||||
- Arrange:
|
||||
- turn 1: no file change
|
||||
- turn 2: file change
|
||||
- turn 3: file change
|
||||
- Assert:
|
||||
- turn counts are monotonic and contiguous in DB (0,1,2,3).
|
||||
- latest checkpoint is marked current.
|
||||
- diffs for adjacent turns map to expected filesystem deltas.
|
||||
|
||||
5. Revert to checkpoint
|
||||
|
||||
- Arrange:
|
||||
- execute 3 turns with at least one file-changing turn.
|
||||
- call `revertToCheckpoint(turnCount=1)`.
|
||||
- Assert:
|
||||
- workspace content matches turn 1 state.
|
||||
- adapter `rollbackThread` called with `numTurns=2`.
|
||||
- DB rows for turns >1 are removed.
|
||||
- later refs are deleted from git.
|
||||
|
||||
6. Capture failure surface
|
||||
|
||||
- Arrange:
|
||||
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
|
||||
- Assert:
|
||||
- `ProviderService` emits `checkpoint/captureError`.
|
||||
- no partial metadata/ref divergence is left behind.
|
||||
|
||||
## WebSocket Coverage (Thin Integration)
|
||||
|
||||
Add one ws server integration spec:
|
||||
|
||||
- Subscribe to `providers.event`.
|
||||
- Run a deterministic provider turn through ws methods.
|
||||
- Assert push stream includes:
|
||||
- `turn/started`, tool events, `turn/completed`, `checkpoint/captured`.
|
||||
- Assert orchestration projection still updates assistant message and turn diff summary.
|
||||
|
||||
## Proposed PR Split
|
||||
|
||||
PR A:
|
||||
|
||||
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
|
||||
|
||||
PR B:
|
||||
|
||||
- Core ProviderService integration specs (cases 1-4).
|
||||
|
||||
PR C:
|
||||
|
||||
- Revert + failure-path specs (cases 5-6) + ws thin integration spec.
|
||||
@@ -0,0 +1,227 @@
|
||||
# Server-Authoritative Event-Sourcing Cleanup Plan
|
||||
|
||||
Goal:
|
||||
|
||||
- Move to a cleaner service architecture with:
|
||||
- durable, server-authoritative event sourcing
|
||||
- strict command routing/validation
|
||||
- pluggable provider adapters
|
||||
- explicit separation between transport, domain orchestration, provider runtime, and persistence
|
||||
|
||||
## Target Service Graph (ASCII)
|
||||
|
||||
```text
|
||||
+---------------------------+
|
||||
| wsServer |
|
||||
| transport |
|
||||
+---------------------------+
|
||||
| orchestration.dispatchCommand
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationCommandRouter |
|
||||
+-------------------------------------------+
|
||||
|
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationCommandHandlers |
|
||||
+-------------------------------------------+
|
||||
|
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationEventStore |
|
||||
+-------------------------------------------+
|
||||
|
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationProjectionService |
|
||||
+-------------------------------------------+
|
||||
| snapshot/replay
|
||||
+---------------------------> wsServer
|
||||
|
||||
|
||||
wsServer -- providers.* RPC --> +---------------------------+
|
||||
| ProviderService |
|
||||
+---------------------------+
|
||||
| |
|
||||
v v
|
||||
+-------------------+ +-------------------------+
|
||||
| ProviderSession | | ProviderAdapterRegistry |
|
||||
| Registry (durable)| +-------------------------+
|
||||
+-------------------+ |
|
||||
^ v
|
||||
| +-------------------------+
|
||||
| | ProviderAdapter(s) |
|
||||
| +-------------------------+
|
||||
| |
|
||||
| runtime events v
|
||||
| +---------------------------+
|
||||
+----------| ProviderRuntimeIngestion |
|
||||
+---------------------------+
|
||||
| | |
|
||||
v v v
|
||||
Router Session Checkpoint
|
||||
Registry Service
|
||||
|
||||
+-------------------------------------------+
|
||||
| CheckpointService |
|
||||
+-------------------------------------------+
|
||||
| | |
|
||||
v v v
|
||||
+--------------------+ +-------------+ +-------------------+
|
||||
| CheckpointCatalog | | Checkpoint | | ProviderAdapter(s)|
|
||||
| (durable) | | Store (git) | | (read/rollback) |
|
||||
+--------------------+ +-------------+ +-------------------+
|
||||
|
|
||||
v
|
||||
+------+
|
||||
|SQLite|
|
||||
+------+
|
||||
|
||||
OrchestrationEventStore ------> SQLite
|
||||
OrchestrationProjectionService -> SQLite
|
||||
ProviderSessionRegistry ------> SQLite
|
||||
CheckpointCatalog ------> SQLite
|
||||
```
|
||||
|
||||
## Commit Series
|
||||
|
||||
### Commit 1: Split public vs system orchestration command contracts
|
||||
|
||||
- Create separate schemas/types:
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `SystemOrchestrationCommandSchema`
|
||||
- `OrchestrationCommandSchema = union(client, system)`
|
||||
- Ensure client transport can only submit client commands.
|
||||
- Keep system commands for server-internal workflows only.
|
||||
- Expected files:
|
||||
- `packages/contracts/src/orchestration.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- orchestration/service tests
|
||||
- Tests:
|
||||
- reject system-only command via WS dispatch path
|
||||
- preserve internal dispatch functionality for system commands
|
||||
|
||||
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
|
||||
|
||||
- Add dedicated router service to validate, authorize, and route commands.
|
||||
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
|
||||
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
|
||||
- Expected files:
|
||||
- `apps/server/src/orchestration/Services/CommandRouter.ts` (new)
|
||||
- `apps/server/src/orchestration/Layers/CommandRouter.ts` (new)
|
||||
- `apps/server/src/orchestration/Layer.ts`
|
||||
- `apps/server/src/orchestration/reducer.ts` (only if needed for event payload changes)
|
||||
- Tests:
|
||||
- router validation and invariant failures
|
||||
- handler happy-path tests per command type
|
||||
|
||||
### Commit 3: Harden event store for idempotency + optimistic append metadata
|
||||
|
||||
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
|
||||
- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
|
||||
- Add optional aggregate version metadata for future optimistic concurrency.
|
||||
- Expected files:
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (new migration)
|
||||
- `apps/server/src/persistence/Services/OrchestrationEvents.ts`
|
||||
- `apps/server/src/persistence/Layers/OrchestrationEvents.ts`
|
||||
- Tests:
|
||||
- duplicate command ID append returns same event/sequence (or explicit idempotent behavior)
|
||||
- concurrent append behavior stays ordered and deterministic
|
||||
|
||||
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
|
||||
|
||||
- Create `ProviderRuntimeIngestionService` that:
|
||||
- subscribes to `ProviderService.streamEvents`
|
||||
- translates runtime events into orchestration commands
|
||||
- dispatches through router/engine
|
||||
- Remove provider-to-orchestration state mutation logic from `wsServer`.
|
||||
- Expected files:
|
||||
- `apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts` (new)
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (new)
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Tests:
|
||||
- ingestion service mapping tests (turn started/completed, message delta/completed, runtime error)
|
||||
- ws integration confirms same external push behavior
|
||||
|
||||
### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
|
||||
|
||||
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
|
||||
- Keep in-memory cache optional, but source of truth must be persistent.
|
||||
- Add startup reconciliation to prune dead sessions / keep known thread mapping.
|
||||
- Expected files:
|
||||
- `apps/server/src/provider/Services/ProviderSessionDirectory.ts` (or new SessionRegistry service)
|
||||
- `apps/server/src/provider/Layers/ProviderSessionDirectory.ts`
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (new table/indexes)
|
||||
- provider persistence tests
|
||||
- Tests:
|
||||
- survives server restart with correct mapping
|
||||
- stale session cleanup semantics
|
||||
|
||||
### Commit 6: Re-key checkpoint metadata from session to thread identity
|
||||
|
||||
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
|
||||
- Keep `session_id` as nullable metadata only.
|
||||
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
|
||||
- Expected files:
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (checkpoint schema migration)
|
||||
- `apps/server/src/persistence/Services/Checkpoints.ts`
|
||||
- `apps/server/src/persistence/Layers/Checkpoints.ts`
|
||||
- `apps/server/src/checkpointing/Layers/CheckpointService.ts`
|
||||
- Tests:
|
||||
- resume/new session over same thread sees same checkpoint history
|
||||
- revert/diff still work after session churn
|
||||
|
||||
### Commit 7: Add durable projection persistence for orchestration read models
|
||||
|
||||
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
|
||||
- Keep event stream as source of truth; projection rebuild stays deterministic.
|
||||
- `getSnapshot` reads from projection store (memory cache optional).
|
||||
- Expected files:
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (projection tables)
|
||||
- `apps/server/src/orchestration/*` projection service/layer
|
||||
- `apps/server/src/wsServer.ts` (snapshot/replay path wiring)
|
||||
- Tests:
|
||||
- cold boot snapshot load without replaying full history in process
|
||||
- projection rebuild from events yields same result as previous reducer semantics
|
||||
|
||||
### Commit 8: Narrow `ProviderService` responsibilities
|
||||
|
||||
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
|
||||
- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
|
||||
- Preserve adapter pluggability and provider-neutral contracts.
|
||||
- Expected files:
|
||||
- `apps/server/src/provider/Layers/ProviderService.ts`
|
||||
- new orchestration/checkpoint runtime coordinator service(s)
|
||||
- Tests:
|
||||
- provider service routing stays intact
|
||||
- checkpoint capture still triggered by turn completion through new coordinator
|
||||
|
||||
### Commit 9: Look over schemas (contracts and events)
|
||||
|
||||
- Scan for unused schemas.
|
||||
- Use effect/Schema everywhere
|
||||
- Analyze which we need
|
||||
- RPC Input/Output (both for routeRequest and command handler)
|
||||
- Event payloads
|
||||
- Persistence entities
|
||||
|
||||
### Commit 10: Remove dead legacy path and finalize docs
|
||||
|
||||
- Remove unused legacy manager/store path from active architecture:
|
||||
- `providerManager.ts`
|
||||
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
|
||||
- Look over effect services for unused methods, errors, etc
|
||||
- Update architecture docs with final service boundaries and boot/runtime graph.
|
||||
- Expected files:
|
||||
- legacy files + references
|
||||
- `AGENTS.md`/docs as needed
|
||||
- `.plans` docs linkage
|
||||
- Tests:
|
||||
- full server integration suite passes on Effect-only path
|
||||
- no regressions in WS protocol behavior
|
||||
|
||||
## Risk Controls
|
||||
|
||||
- Keep WS method names and payload contracts stable throughout.
|
||||
- Gate each commit with targeted integration tests before moving forward.
|
||||
- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
|
||||
@@ -0,0 +1,11 @@
|
||||
Rewrite `createServer` and `index.ts` to be Effect native.
|
||||
|
||||
Maybe use `effect/unstable/Socket` for the web socket server
|
||||
|
||||
- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts
|
||||
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
|
||||
|
||||
- Migrate remaining runtime code to Effect
|
||||
- `gitManager` -> `src/git`
|
||||
- `terminalManager` -> `src/terminal` (Manager + PTY)
|
||||
- ...
|
||||
@@ -0,0 +1,165 @@
|
||||
# PR #89 Review Remediation Plan (Phased)
|
||||
|
||||
## How To Use These Files
|
||||
|
||||
- Working checklist with updateable status per item (single source of truth): `.plans/16c-pr89-remediation-checklist.md`
|
||||
- This file (`16-pr89-review-remediation-phases.md`): phase strategy and grouping.
|
||||
|
||||
## Scope
|
||||
|
||||
- Source: GitHub review comments on PR #89 (`Add server-side orchestration engine with event sourcing`).
|
||||
- Triage baseline used here:
|
||||
- Total threads: 185
|
||||
- Outdated: 94 (excluded)
|
||||
- Active unresolved: 85
|
||||
- Invalid/false-positive: 3 (excluded)
|
||||
- Duplicate reposts: collapsed
|
||||
- Unique actionable findings after filtering: 58
|
||||
- Post-rewrite validity audit: 5 additional stale items marked invalid, leaving 53 actionable (`34 valid` + `19 partially-valid`)
|
||||
|
||||
## Phase 0: Canonical Triage Lock
|
||||
|
||||
- Create a single tracking checklist for the 53 currently actionable findings.
|
||||
- Map every duplicate thread to its canonical item.
|
||||
- Mark invalid/false-positive items with explicit rationale.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Every open thread is mapped to one canonical fix item or marked invalid.
|
||||
|
||||
## Phase 1: Runtime Survival and Critical Event Wiring
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Worker loop/fiber fatal error handling in orchestration reactors.
|
||||
- WebSocket message error boundaries and unhandled rejection guards.
|
||||
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
|
||||
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- A single event-processing failure cannot permanently stop ingestion/reactor loops.
|
||||
- WS message handling cannot produce unhandled promise rejections.
|
||||
- Invalid provider-event-channel review findings are closed with architecture rationale.
|
||||
|
||||
## Phase 2: State Consistency and Ordering
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Fire-and-forget revert completion causing consistency windows.
|
||||
- Non-atomic append/projection paths and retry behavior.
|
||||
- Race-sensitive thread/event association issues.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
|
||||
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Revert flow is deterministically reflected in read model updates.
|
||||
- Append/project failure mode is explicit and safe under retry.
|
||||
- No cross-thread misassociation under concurrent runtime events.
|
||||
|
||||
## Phase 3: Checkpointing Correctness Bundle
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Checkpoint input normalization consistency.
|
||||
- Snapshot/projector coverage mismatches.
|
||||
- Checkpoint ref/workspace CWD utility duplication.
|
||||
- Checkpoint diff/error handling behavior gaps.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
|
||||
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
|
||||
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Checkpoint capture/restore/revert paths use one normalization policy.
|
||||
- Required projectors are actually represented in snapshot reads.
|
||||
- Shared checkpoint/ref/CWD helpers are centralized.
|
||||
|
||||
## Phase 4: Memory and Lifecycle Hygiene
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Unbounded in-memory dedup sets/maps.
|
||||
- Missing cleanup/lifecycle protections in long-lived effects/resources.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
|
||||
- `apps/server/src/config.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Long-running server memory does not grow unbounded from dedup bookkeeping.
|
||||
- Resource cleanup paths are registered for interruption/shutdown.
|
||||
|
||||
## Phase 5: Transport, Parsing, and Platform Edge Cases
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- UTF-8 chunk boundary decode correctness.
|
||||
- Markdown/file-link parsing edge cases.
|
||||
- Shell/OS-specific PATH parsing behavior.
|
||||
- Git rename parsing and small keybinding edge cases.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- `apps/server/src/git/Layers/CodexTextGeneration.ts`
|
||||
- `apps/web/src/markdown-links.ts`
|
||||
- `apps/server/src/os-jank.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `apps/server/src/keybindings.ts`
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Edge-case parsers are robust across valid but non-trivial inputs.
|
||||
- Platform-dependent command behavior has safe fallbacks.
|
||||
|
||||
## Phase 6: Build and Maintainability Cleanup
|
||||
|
||||
Related bug groups solved together:
|
||||
|
||||
- Build script/runtime assumption cleanup.
|
||||
- Redundant error-union declarations and utility/type duplication.
|
||||
- Non-functional cleanup comments/docs markers.
|
||||
|
||||
Primary files:
|
||||
|
||||
- `apps/server/package.json`
|
||||
- `apps/server/src/checkpointing/Errors.ts`
|
||||
- Shared utility locations introduced during earlier phases
|
||||
- `AGENTS.md` (if cleanup is still pending)
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Build path is explicit and environment-safe.
|
||||
- Redundant types/utilities are removed in favor of single sources of truth.
|
||||
|
||||
## Phase 7: Verification and Closeout
|
||||
|
||||
- Add backend tests for all behavioral fixes (integration-focused; external services may be layered/mocked, core business logic not mocked out).
|
||||
- Run lint and backend tests for all touched packages.
|
||||
- Resolve threads with fix references per canonical checklist item.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Lint passes.
|
||||
- Backend tests pass.
|
||||
- All actionable review threads are resolved or explicitly justified.
|
||||
@@ -0,0 +1,478 @@
|
||||
# PR #89 Remediation Checklist (Consolidated)
|
||||
|
||||
_Last updated: 2026-02-26_
|
||||
|
||||
This is the working checklist for remediation execution.
|
||||
|
||||
Status values:
|
||||
|
||||
- `TODO`: Not started
|
||||
- `IN_PROGRESS`: Currently being worked
|
||||
- `BLOCKED`: Waiting on decision/dependency
|
||||
- `DONE`: Implemented and verified
|
||||
- `CLOSED_INVALID`: Stale/invalid review finding
|
||||
|
||||
Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
|
||||
|
||||
## Active Checklist
|
||||
|
||||
### Phase 1
|
||||
|
||||
- [x] `C002` A dispatch error in `processEvent` will terminate the `Effect.forever` loop, permanently halting event ingestion. Consider adding error recovery (e.g., `Effect.catchAll` with logging) around `processEvent` so failures don't kill the fiber.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `High`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:333`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cH, PRRT_kwDORLtfbc5wnWwF, PRRT_kwDORLtfbc5wyTaP, PRRT_kwDORLtfbc5wzliw, PRRT_kwDORLtfbc5w0_g3, PRRT_kwDORLtfbc5w1HGT (+5 duplicate thread(s))
|
||||
- Audit note: Ingestion worker loop can terminate on unhandled processEvent failure.
|
||||
|
||||
- [x] `C003` Consider attaching a no-op error listener before `socket.write` (e.g., `socket.on('error', () => {})`) to prevent an unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `High`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:75`
|
||||
- Threads: PRRT_kwDORLtfbc5v-cf4
|
||||
- Audit note: Upgrade reject writes then destroys socket without defensive error listener.
|
||||
|
||||
- [x] `C012` Forked revert dispatch risks read model inconsistency
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:542`
|
||||
- Threads: PRRT_kwDORLtfbc5whszW, PRRT_kwDORLtfbc5wyTaS, PRRT_kwDORLtfbc5wzli0, PRRT_kwDORLtfbc5w0_g4, PRRT_kwDORLtfbc5w1HGX (+4 duplicate thread(s))
|
||||
- Audit note: Revert completion dispatch remains forked; state consistency window remains.
|
||||
|
||||
- [ ] `C019` ProviderRuntimeIngestion processes events for wrong thread on race
|
||||
- Status: `TODO`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:178`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaL
|
||||
- Audit note: SessionId-only routing can misassociate events under races/rebinds.
|
||||
|
||||
- [x] `C020` On `message.completed`, the message ID is added to the set and `thread.message.assistant.complete` is dispatched. On `turn.completed`, the same set is iterated and `thread.message.assistant.complete` is dispatched again for each ID—including already-completed ones. Consider removing message IDs from the set after dispatching on `message.completed`, or filtering out already-completed IDs before the `turn.completed` loop.
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:266`
|
||||
- Threads: PRRT_kwDORLtfbc5w1GPr
|
||||
- Audit note: Duplicate complete dispatch exists; downstream impact often idempotent.
|
||||
|
||||
- [x] `C026` Consider adding `.catch(() => {})` after `Effect.runPromise(handleMessage(ws, raw))` to prevent unhandled rejections from crashing the server if `encodeResponse` or setup logic fails.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:545`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cE
|
||||
- Audit note: runPromise result still not caught; rejection can surface unhandled.
|
||||
|
||||
- [x] `C027` WS message handler can cause unhandled promise rejection
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/wsServer.ts:545`
|
||||
- Threads: PRRT_kwDORLtfbc5wyTaW, PRRT_kwDORLtfbc5wzli3 (+1 duplicate thread(s))
|
||||
- Audit note: Same unhandled rejection path remains in WS message handler.
|
||||
|
||||
- [x] `C042` Duplicated `resolveThreadWorkspaceCwd` across three files
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62`
|
||||
- Threads: PRRT_kwDORLtfbc5wzli2
|
||||
- Audit note: Duplication exists but one instance is variant logic, so impact is moderate.
|
||||
|
||||
- [x] `C043` Duplicated workspace CWD resolution logic across reactor modules
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62`
|
||||
- Threads: PRRT_kwDORLtfbc5wnWwM, PRRT_kwDORLtfbc5w1C3-, PRRT_kwDORLtfbc5w1HGZ (+2 duplicate thread(s))
|
||||
- Audit note: Workspace CWD resolution duplication still present across modules.
|
||||
|
||||
- [x] `C044` Checkpoint reactor swallows diff errors silently for `turn.completed`
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:274`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaO
|
||||
- Audit note: Errors are swallowed to empty diff with warning; not fully silent but still lossy.
|
||||
|
||||
- [x] `C045` `truncateDetail` slices to `limit - 1` then appends `"..."` (3 chars), producing strings of length `limit + 2`. Consider slicing to `limit - 3` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:29`
|
||||
- Threads: PRRT_kwDORLtfbc5wzp4R
|
||||
- Audit note: truncateDetail still overshoots limit.
|
||||
|
||||
- [x] `C046` `latestMessageIdByTurnKey` is written to but never read, and `clearAssistantMessageIdsForTurn` doesn't clear its entries—only `clearTurnStateForSession` does. Consider removing this map entirely if unused, or clearing it alongside `turnMessageIdsByTurnKey` in `clearAssistantMessageIdsForTurn`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:133`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIQ
|
||||
- Audit note: latestMessageIdByTurnKey still unused/unpruned in per-turn clear path.
|
||||
|
||||
- [x] `C053` Consider using `socket.end(response)` instead of `socket.write(response)` + `socket.destroy()` to ensure the HTTP error response is fully flushed before closing the connection.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:83`
|
||||
- Threads: PRRT_kwDORLtfbc5v-WPD
|
||||
- Audit note: Still uses write+destroy rather than end() for rejection response.
|
||||
|
||||
- [ ] `C054` When array chunks contain a multi-byte UTF-8 character split across boundaries, decoding each chunk separately produces replacement characters. Consider using `Buffer.concat()` on all chunks before calling `.toString("utf8")`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:104`
|
||||
- Threads: PRRT_kwDORLtfbc5whtrR
|
||||
- Audit note: Array chunk UTF-8 decode remains vulnerable to split multibyte corruption.
|
||||
|
||||
- [x] `C059` Suggestion: don’t spread `params` into `body`; it can override `_tag` and mishandle non-object values. Keep `_tag` separate and nest `params` under a single key (e.g., `data`), or validate `params` is a plain object.
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/web/src/wsTransport.ts:59`
|
||||
- Threads: PRRT_kwDORLtfbc5whtrN
|
||||
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
|
||||
|
||||
### Phase 2
|
||||
|
||||
- [x] `C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `High`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:96`
|
||||
- Threads: PRRT_kwDORLtfbc5wzp4T
|
||||
- Audit note: Append/project/receipt are non-atomic; retry can duplicate events.
|
||||
|
||||
- [x] `C013` If `projectionPipeline.projectEvent` fails after `eventStore.append` succeeds, the event is persisted but `readModel` isn't updated, causing desync. Consider updating the in-memory `readModel` immediately after append (before the external projection), so local state stays consistent regardless of downstream failures.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:99`
|
||||
- Threads: PRRT_kwDORLtfbc5whtrM
|
||||
- Audit note: Persisted event can outpace in-memory projection on mid-flight failure.
|
||||
|
||||
- [x] `C015` The gap-filling fallback logic can retain messages from turns that are about to be deleted, causing foreign key violations. Consider removing the fallback logic entirely, or filtering `fallbackUserMessages` and `fallbackAssistantMessages` to only include messages whose `turnId` is in `retainedTurnIds`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:99`
|
||||
- Threads: PRRT_kwDORLtfbc5whxJO
|
||||
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
|
||||
|
||||
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:490`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvH8
|
||||
- Audit note: Pending turn-start map is in-memory only and not rebuilt on bootstrap.
|
||||
|
||||
### Phase 3
|
||||
|
||||
- [x] `C008` Inconsistent input normalization across CheckpointStore methods
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`
|
||||
- Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
|
||||
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
|
||||
|
||||
- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts:71`
|
||||
- Threads: PRRT_kwDORLtfbc5wiLhQ
|
||||
- Audit note: Snapshot sequence can under-report due to extra projectors, but replay impact is lower now.
|
||||
|
||||
- [x] `C033` Three error classes defined but never instantiated anywhere
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Errors.ts:51`
|
||||
- Threads: PRRT_kwDORLtfbc5wlYgo
|
||||
- Audit note: Original claim overstated; some errors used, others appear unused.
|
||||
|
||||
- [x] `C034` Redundant `CheckpointInvariantError` in `CheckpointServiceError` union type
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Errors.ts:79`
|
||||
- Threads: PRRT_kwDORLtfbc5wj5fn
|
||||
- Audit note: CheckpointInvariantError remains redundantly included in service union.
|
||||
|
||||
- [x] `C035` Redundant error type in CheckpointServiceError union definition
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Errors.ts:79`
|
||||
- Threads: PRRT_kwDORLtfbc5wlYgs, PRRT_kwDORLtfbc5wxsO6, PRRT_kwDORLtfbc5w1C4B (+2 duplicate thread(s))
|
||||
- Audit note: Same as C034.
|
||||
|
||||
### Phase 4
|
||||
|
||||
- [ ] `C018` Unbounded memory growth in turn start deduplication set
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Memory/resource growth`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts:84`
|
||||
- Threads: PRRT_kwDORLtfbc5whszQ, PRRT_kwDORLtfbc5wl2A8, PRRT_kwDORLtfbc5wyTaT, PRRT_kwDORLtfbc5wzliz, PRRT_kwDORLtfbc5w0_g-, PRRT_kwDORLtfbc5w1HGW (+5 duplicate thread(s))
|
||||
- Audit note: handledTurnStartKeys still grows without pruning.
|
||||
|
||||
### Phase 5
|
||||
|
||||
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/git/Layers/GitCore.ts:41`
|
||||
- Threads: PRRT_kwDORLtfbc5w1CxT
|
||||
- Audit note: Braced rename parsing still breaks paths like src/{old => new}/file.ts.
|
||||
|
||||
- [ ] `C010` `loadCustomKeybindingsConfig` fails when the config file doesn't exist, which is expected for new users. Consider catching `ENOENT` and returning an empty array instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/keybindings.ts:418`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIJ
|
||||
- Audit note: ENOENT for missing keybindings config still not handled as empty/default.
|
||||
|
||||
- [ ] `C022` Fish shell outputs `$PATH` as space-separated, not colon-separated. Consider checking if the shell is fish and using `string join : $PATH` instead, or validating the result contains colons before assigning.
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/os-jank.ts:10`
|
||||
- Threads: PRRT_kwDORLtfbc5wkRZM
|
||||
- Audit note: fish PATH formatting risk still exists in os-jank path recovery.
|
||||
|
||||
- [ ] `C023` Using `-il` flags causes the shell to source profile scripts that may print banners or other text, polluting the captured `PATH`. Consider using `-lc` (login only, non-interactive) to reduce unwanted output.
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/os-jank.ts:10`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cM
|
||||
- Audit note: -ilc shell invocation can pollute captured PATH output.
|
||||
|
||||
- [x] `C029` `parseFileUrlHref` already decodes the path (line 46), but `safeDecode` is called again here, corrupting filenames containing `%` sequences. Consider skipping the decode when `fileUrlTarget` is non-null.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/web/src/markdown-links.ts:105`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsU
|
||||
- Audit note: file URL decoding still double-decodes in one path.
|
||||
|
||||
- [x] `C030` `EXTERNAL_SCHEME_PATTERN` matches `script.ts:10` as a scheme because `.ts:` looks like `scheme:`. Consider requiring `://` after the colon, or checking that what follows the colon is not just digits. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/web/src/markdown-links.ts:111`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsK
|
||||
- Audit note: Scheme regex still misclassifies script.ts:10 as external scheme.
|
||||
|
||||
- [ ] `C038` Multi-byte UTF-8 characters split across chunks will be corrupted when decoding each chunk separately. Consider accumulating all chunks first, then decoding once, or use `TextDecoder` with `stream: true`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/git/Layers/CodexTextGeneration.ts:136`
|
||||
- Threads: PRRT_kwDORLtfbc5w1GPo
|
||||
- Audit note: Chunk-by-chunk UTF-8 decode can still corrupt split multibyte characters.
|
||||
|
||||
- [x] `C039` The `+` key can be parsed (via trailing `+` handling) but cannot be encoded because `shortcut.key.includes("+")` returns true for the literal `+` key. Consider checking `shortcut.key === "+"` separately and encoding it as `"space"` style (e.g., a special token), or adjusting the condition to allow the single `+` character. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/keybindings.ts:352`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIB
|
||||
- Audit note: Parser/encoder mismatch remains, but encoder path currently low-use.
|
||||
|
||||
- [x] `C040` `upsertKeybindingRule` has a race condition: concurrent calls read the same file state, then the last write overwrites earlier changes. Consider wrapping the read-modify-write sequence with `Effect.Semaphore` to serialize access. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/keybindings.ts:488`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIA
|
||||
- Audit note: upsertKeybindingRule read-modify-write remains race-prone.
|
||||
|
||||
### Phase 6
|
||||
|
||||
- [ ] `C028` Branch sync dispatches both server and stale local update
|
||||
- Status: `TODO`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/components/BranchToolbar.tsx:102`
|
||||
- Threads: PRRT_kwDORLtfbc5v-XCu
|
||||
- Audit note: Optimistic local+server dual update is intentional but can temporarily diverge.
|
||||
|
||||
- [x] `C037` `Effect.callback` should return a cleanup function to close the server(s) on fiber interruption. Without it, the `Net.Server` handles keep the process alive and leak the port if the effect is cancelled. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/config.ts:41`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cO
|
||||
- Audit note: Callback cleanup missing, but practical exposure is low in one-shot startup path.
|
||||
|
||||
- [ ] `C047` `SqlSchema.findOneOption` can produce both SQL errors and decode errors, but `mapError` wraps all as `PersistenceSqlError`. Consider distinguishing `ParseError` from SQL errors and mapping decode failures to `PersistenceDecodeError` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts:75`
|
||||
- Threads: PRRT_kwDORLtfbc5wiaR-
|
||||
- Audit note: Decode and SQL errors still collapsed into one persistence error kind.
|
||||
|
||||
- [x] `C049` `JSON.stringify(cause)` returns `undefined` for `undefined`, functions, or symbols, violating the `string` return type. Consider coercing the result to a string (e.g., `String(JSON.stringify(cause))`) or adding a fallback.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/provider/Layers/ProviderService.ts:59`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsI
|
||||
- Audit note: JSON.stringify(cause) may return undefined despite string expectations.
|
||||
|
||||
- [ ] `C050` The read-modify-write pattern (`getBySessionId` → merge → `upsert`) is susceptible to lost updates under concurrent writes. Consider wrapping in a transaction or adding optimistic concurrency control (e.g., version field) if concurrent session updates are expected. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:94`
|
||||
- Threads: PRRT_kwDORLtfbc5wiLhY
|
||||
- Audit note: ProviderSessionDirectory upsert remains read-merge-write without concurrency control.
|
||||
|
||||
- [x] `C051` Using `??` for `providerThreadId` and `adapterKey` makes it impossible to clear these fields by passing `null`, since `null ?? existing` evaluates to `existing`. Consider using explicit `undefined` checks (like `resumeCursor` does) if clearing should be supported. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:119`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvH9
|
||||
- Audit note: Null-clearing issue is real for providerThreadId; adapterKey part overstated.
|
||||
|
||||
- [ ] `C052` Race condition: `processHandle` may be `null` when `data` callback fires, since it's assigned after `Bun.spawn` returns. Consider initializing `BunPtyProcess` first, then passing it to the callback to avoid losing initial output. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/terminal/Layers/BunPTY.ts:97`
|
||||
- Threads: PRRT_kwDORLtfbc5w1CxE
|
||||
- Audit note: Data callback may race before processHandle assignment.
|
||||
|
||||
- [ ] `C056` When `onOpenChange` is provided without `open`, the internal `_open` state never updates because `setOpenProp` takes precedence. Consider calling `_setOpen` when `openProp === undefined`, regardless of whether `setOpenProp` exists.
|
||||
- Status: `TODO`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/components/ui/sidebar.tsx:114`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIq
|
||||
- Audit note: Bug pattern exists, but current callsites mostly avoid triggering it.
|
||||
|
||||
- [ ] `C057` The `resizable` object is recreated on every render, causing `SidebarRail`'s `useEffect` to repeatedly read localStorage and update the DOM. Consider memoizing the object with `useMemo`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/routes/_chat.$threadId.tsx:105`
|
||||
- Threads: PRRT_kwDORLtfbc5wyWz4
|
||||
- Audit note: Resizable object recreation still retriggers effect/storage reads.
|
||||
|
||||
- [ ] `C058` When `localStorage.getItem()` returns `null`, `Number(null)` evaluates to `0`, which passes `Number.isFinite(0)`. This causes the sidebar to clamp to `minWidth` on first load, overriding the `DIFF_INLINE_DEFAULT_WIDTH` CSS clamp. Consider checking for `null` or empty string before parsing, e.g. guard with `storedWidth === null || storedWidth === ''`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/routes/_chat.$threadId.tsx:122`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsX
|
||||
- Audit note: Number(null) -> 0 path still forces min width on initial load.
|
||||
|
||||
- [ ] `C060` `defaultModel` should be `Schema.optional(Schema.NullOr(Schema.String))` to allow clearing the value. Currently there's no way to reset it to `null` since omitting means "no change" in patch semantics. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `packages/contracts/src/orchestration.ts:253`
|
||||
- Threads: PRRT_kwDORLtfbc5whxJC
|
||||
- Audit note: Schema still cannot express null clear for defaultModel patch.
|
||||
|
||||
## Closed Invalid Items
|
||||
|
||||
- [x] `C014` Engine error handler catches all errors including non-invariant ones
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:144`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaJ
|
||||
- Rationale: Broad catch is intentional for worker liveness; transactional dispatch path prevents the claimed non-invariant idempotency break in current design.
|
||||
|
||||
- [x] `C021` Shared mutable default metadata object causes stale eventId
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/server/src/orchestration/decider.ts:27`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaA
|
||||
- Rationale: Stale-eventId claim no longer applies; eventId is regenerated per event.
|
||||
|
||||
- [x] `C025` Duplicated checkpoint ref computation across two files
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/server/src/wsServer.ts:128`
|
||||
- Threads: PRRT_kwDORLtfbc5wvwag
|
||||
- Rationale: No longer duplicated; checkpoint ref helper now centralized.
|
||||
|
||||
- [x] `C031` Revert uses wrong turn count from positional inference
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/web/src/session-logic.ts:127`
|
||||
- Threads: PRRT_kwDORLtfbc5v9SCp
|
||||
- Rationale: Revert now uses explicit checkpointTurnCount first; positional fallback is non-primary.
|
||||
|
||||
- [x] `C036` Duplicate `checkpointRefForThreadTurn` function in two production files
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Low`
|
||||
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:284`
|
||||
- Threads: PRRT_kwDORLtfbc5wiqFX
|
||||
- Rationale: No longer duplicated; single production source via Refs.ts.
|
||||
|
||||
- [x] `C055` Duplicate `checkpointRefForThreadTurn` function across files
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Low`
|
||||
- File: `apps/server/src/wsServer.ts:128`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaG
|
||||
- Rationale: No longer duplicated; helper is centralized.
|
||||
@@ -0,0 +1,441 @@
|
||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
||||
|
||||
## Why this plan was rewritten
|
||||
|
||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
||||
|
||||
1. `orchestration.dispatchCommand` (client intent)
|
||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
||||
|
||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
||||
|
||||
---
|
||||
|
||||
## Current constraints to design around (post-Stage 1)
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
|
||||
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
|
||||
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
||||
|
||||
---
|
||||
|
||||
## Architecture target
|
||||
|
||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
||||
|
||||
Key decisions:
|
||||
|
||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Contracts and command shape updates
|
||||
|
||||
### 1.1 Provider-aware model contract
|
||||
|
||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
||||
|
||||
Expected outcomes:
|
||||
|
||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
||||
2. Add helpers that resolve model by provider.
|
||||
3. Preserve backwards compatibility for existing Codex defaults.
|
||||
|
||||
### 1.2 Turn-start provider intent
|
||||
|
||||
Update `packages/contracts/src/orchestration.ts`:
|
||||
|
||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
||||
3. Keep existing command valid when provider is omitted.
|
||||
|
||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
||||
|
||||
### 1.3 Provider session start input for Claude runtime knobs (completed)
|
||||
|
||||
Update `packages/contracts/src/provider.ts`:
|
||||
|
||||
1. Move provider-specific start fields into typed `providerOptions`:
|
||||
- `providerOptions.codex`
|
||||
- `providerOptions.claudeCode`
|
||||
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
|
||||
3. Deprecate/remove `resumeThreadId` from the generic start contract.
|
||||
4. Treat `resumeCursor` as adapter-owned opaque state.
|
||||
|
||||
### 1.4 Contract tests (completed)
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Breaking-change expectations for removed top-level provider fields.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
|
||||
|
||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
|
||||
### 2.1.a SDK dependency and baseline config
|
||||
|
||||
Add server dependency:
|
||||
|
||||
1. `@anthropic-ai/claude-agent-sdk`
|
||||
|
||||
Baseline adapter options to support from day one:
|
||||
|
||||
1. `cwd`
|
||||
2. `model`
|
||||
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
|
||||
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
|
||||
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
|
||||
6. `resume`
|
||||
7. `resumeSessionAt`
|
||||
8. `includePartialMessages`
|
||||
9. `canUseTool`
|
||||
10. `hooks`
|
||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
||||
|
||||
### 2.2 Claude runtime bridge
|
||||
|
||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
||||
|
||||
Required capabilities:
|
||||
|
||||
1. Long-lived session context per adapter session.
|
||||
2. Multi-turn input queue.
|
||||
3. Interrupt support.
|
||||
4. Approval request/response bridge.
|
||||
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
|
||||
|
||||
#### 2.2.a Agent SDK details to preserve
|
||||
|
||||
The adapter should explicitly rely on these SDK capabilities:
|
||||
|
||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
||||
2. Multi-turn input is supported via async-iterable prompt input.
|
||||
3. Tool approval decisions are provided via `canUseTool`.
|
||||
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
|
||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
||||
|
||||
#### 2.2.b Effect-native session lifecycle skeleton
|
||||
|
||||
```ts
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { Effect } from "effect";
|
||||
|
||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const claudeOptions = input.providerOptions?.claudeCode;
|
||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
||||
const abortController = new AbortController();
|
||||
const result = query({
|
||||
prompt: makePromptAsyncIterable(),
|
||||
options: {
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
permissionMode: claudeOptions?.permissionMode,
|
||||
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
|
||||
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
|
||||
resume: resumeState?.threadId,
|
||||
resumeSessionAt: resumeState?.sessionAt,
|
||||
signal: abortController.signal,
|
||||
includePartialMessages: true,
|
||||
canUseTool: makeCanUseTool(),
|
||||
hooks: makeClaudeHooks(),
|
||||
},
|
||||
});
|
||||
return { abortController, result };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId: "pending",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
||||
);
|
||||
```
|
||||
|
||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
||||
|
||||
Preferred when available in the pinned Effect version:
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
||||
session.result,
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Portable fallback (already aligned with current server patterns):
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
for await (const message of session.result) {
|
||||
if (cancelled) break;
|
||||
emit.single(message);
|
||||
}
|
||||
emit.end();
|
||||
} catch (cause) {
|
||||
emit.fail(
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
return Effect.sync(() => {
|
||||
cancelled = true;
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### 2.3 Canonical event mapping
|
||||
|
||||
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
|
||||
|
||||
Initial mapping target:
|
||||
|
||||
1. assistant text deltas -> `content.delta`
|
||||
2. final assistant text -> `item.completed` and/or `turn.completed`
|
||||
3. approval requests -> `request.opened`
|
||||
4. approval results -> `request.resolved`
|
||||
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
|
||||
6. errors -> `runtime.error`
|
||||
7. plan/proposed-plan content when derivable
|
||||
|
||||
Implementation note:
|
||||
|
||||
1. Keep raw Claude message on `raw` for debugging.
|
||||
2. Prefer canonical item/request kinds over provider-native enums.
|
||||
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
|
||||
|
||||
### 2.4 Resume cursor strategy
|
||||
|
||||
Define Claude-owned opaque resume state, e.g.:
|
||||
|
||||
```ts
|
||||
interface ClaudeResumeCursor {
|
||||
readonly version: 1;
|
||||
readonly threadId?: string;
|
||||
readonly sessionAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Serialize only adapter-owned state into `resumeCursor`.
|
||||
2. Parse/validate only inside Claude adapter.
|
||||
3. Store updated cursor when Claude runtime yields enough data to resume safely.
|
||||
4. Never overload orchestration thread id as Claude thread id.
|
||||
|
||||
### 2.5 Interrupt and stop semantics
|
||||
|
||||
Map orchestration stop/interrupt expectations onto SDK controls:
|
||||
|
||||
1. `interruptTurn()` -> active query interrupt.
|
||||
2. `stopSession()` -> close session resources and prevent future sends.
|
||||
3. `rollbackThread()` -> see Phase 4.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Provider service and composition
|
||||
|
||||
### 3.1 Register Claude adapter
|
||||
|
||||
Update provider registry layer to include Claude:
|
||||
|
||||
1. add `claudeCode` -> `ClaudeAdapter`
|
||||
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
|
||||
|
||||
### 3.2 Persist provider binding
|
||||
|
||||
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
|
||||
|
||||
Required validation:
|
||||
|
||||
1. Claude bindings survive restart.
|
||||
2. resume cursor remains opaque and round-trips untouched.
|
||||
3. stopAll + restart can recover Claude sessions when possible.
|
||||
|
||||
### 3.3 Provider start routing
|
||||
|
||||
Update `ProviderCommandReactor` / orchestration flow:
|
||||
|
||||
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
|
||||
2. If a thread already has Claude session binding, reuse it.
|
||||
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Checkpoint and revert strategy
|
||||
|
||||
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
|
||||
|
||||
Pick one explicit strategy:
|
||||
|
||||
### Option A: provider-native rewind
|
||||
|
||||
If SDK/runtime supports safe rewind:
|
||||
|
||||
1. implement in Claude adapter
|
||||
2. keep `CheckpointReactor` unchanged
|
||||
|
||||
### Option B: session restart + state truncation shim
|
||||
|
||||
If no native rewind exists:
|
||||
|
||||
1. Claude adapter returns successful rollback by:
|
||||
- stopping current Claude session
|
||||
- clearing/rewriting stored Claude resume cursor to last safe resumable point
|
||||
- forcing next turn to recreate session from persisted orchestration state
|
||||
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
|
||||
|
||||
Whichever option is chosen:
|
||||
|
||||
1. behavior must be deterministic
|
||||
2. checkpoint revert tests must pass under orchestration expectations
|
||||
3. user-visible activity log should explain failures clearly when provider rollback is impossible
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Web integration
|
||||
|
||||
### 5.1 Provider picker and model picker
|
||||
|
||||
Update web state/UI:
|
||||
|
||||
1. allow choosing Claude as thread provider before first turn
|
||||
2. show Claude model list from provider-aware model helpers
|
||||
3. preserve existing Codex default behavior when provider omitted
|
||||
|
||||
Likely touch points:
|
||||
|
||||
1. `apps/web/src/store.ts`
|
||||
2. `apps/web/src/components/ChatView.tsx`
|
||||
3. `apps/web/src/types.ts`
|
||||
4. `packages/shared/src/model.ts`
|
||||
|
||||
### 5.2 Settings for Claude executable/options
|
||||
|
||||
Add app settings if needed for:
|
||||
|
||||
1. Claude binary path
|
||||
2. default permission mode
|
||||
3. default max thinking tokens
|
||||
|
||||
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
|
||||
|
||||
### 5.3 Session rendering
|
||||
|
||||
No new WS channel should be needed. Claude should appear through existing:
|
||||
|
||||
1. thread messages
|
||||
2. activities/worklog
|
||||
3. approvals
|
||||
4. session state
|
||||
5. checkpoints/diffs
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Testing strategy
|
||||
|
||||
### 6.1 Contract tests
|
||||
|
||||
Cover:
|
||||
|
||||
1. provider-aware model schemas
|
||||
2. provider field on turn-start command
|
||||
3. provider-specific start options schema
|
||||
|
||||
### 6.2 Adapter layer tests
|
||||
|
||||
Add `ClaudeAdapter.test.ts` covering:
|
||||
|
||||
1. session start
|
||||
2. event mapping
|
||||
3. approval bridge
|
||||
4. resume cursor parse/serialize
|
||||
5. interrupt behavior
|
||||
6. rollback behavior or explicit unsupported error path
|
||||
|
||||
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
|
||||
|
||||
### 6.3 Provider service integration tests
|
||||
|
||||
Extend provider integration coverage so Claude is exercised through `ProviderService`:
|
||||
|
||||
1. start Claude session
|
||||
2. send turn
|
||||
3. receive canonical runtime events
|
||||
4. restart/recover using persisted binding
|
||||
|
||||
### 6.4 Orchestration integration tests
|
||||
|
||||
Add/extend integration tests around:
|
||||
|
||||
1. first-turn provider selection
|
||||
2. Claude approval requests routed through orchestration
|
||||
3. Claude runtime ingestion -> messages/activities/session updates
|
||||
4. checkpoint revert behavior under Claude
|
||||
5. stopAll/restart recovery
|
||||
|
||||
These should validate real orchestration flows, not just adapter behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Rollout order
|
||||
|
||||
Recommended implementation order:
|
||||
|
||||
1. contracts/provider-aware models
|
||||
2. provider field on turn-start
|
||||
3. Claude adapter skeleton + start/send/stream
|
||||
4. canonical event mapping
|
||||
5. provider registry/service wiring
|
||||
6. orchestration recovery + checkpoint strategy
|
||||
7. web provider/model picker
|
||||
8. full integration tests
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
1. Reintroducing provider-specific WS methods/channels.
|
||||
2. Storing provider-native thread ids as orchestration ids.
|
||||
3. Bypassing orchestration engine for Claude-specific UI flows.
|
||||
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
|
||||
@@ -0,0 +1,109 @@
|
||||
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
|
||||
|
||||
## Summary
|
||||
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
|
||||
|
||||
## Implementation Status
|
||||
|
||||
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
|
||||
|
||||
### New files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
|
||||
| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) |
|
||||
| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence |
|
||||
| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing |
|
||||
| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced |
|
||||
| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation |
|
||||
| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable |
|
||||
| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) |
|
||||
| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests |
|
||||
| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests |
|
||||
|
||||
### Key modifications
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` |
|
||||
| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness |
|
||||
| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher |
|
||||
| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel |
|
||||
| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages |
|
||||
| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts |
|
||||
| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing |
|
||||
| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion |
|
||||
| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops |
|
||||
|
||||
## Key Changes
|
||||
### 1. Strengthen the generic boundaries, not the Codex boundary — DONE
|
||||
- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade.
|
||||
- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`.
|
||||
- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract.
|
||||
|
||||
### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE
|
||||
- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
|
||||
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
|
||||
- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
|
||||
- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
|
||||
|
||||
### 3. Introduce explicit server readiness and a single push pipeline — DONE
|
||||
- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
|
||||
- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
|
||||
- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
|
||||
- `wsServer.ts` no longer publishes directly from ad hoc background streams.
|
||||
|
||||
### 4. Turn background watchers into explicit runtimes — DONE
|
||||
- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
|
||||
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
|
||||
- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
|
||||
|
||||
### 5. Replace polling-based orchestration waiting with receipts — DONE
|
||||
- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
|
||||
- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
|
||||
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
|
||||
|
||||
### 6. Centralize client transport state and decoding — DONE
|
||||
- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
|
||||
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
|
||||
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
|
||||
|
||||
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
|
||||
- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
|
||||
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
|
||||
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
|
||||
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
|
||||
|
||||
## Provider-Coupling Guardrails
|
||||
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
|
||||
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
|
||||
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
|
||||
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
|
||||
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
|
||||
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
|
||||
|
||||
## Test Plan
|
||||
- Contracts:
|
||||
- schema tests for typed push envelopes and structured decode diagnostics
|
||||
- ordering tests for `sequence`
|
||||
- Server:
|
||||
- readiness tests proving `server.welcome` cannot precede runtime readiness
|
||||
- push bus tests proving terminal/config/orchestration pushes are serialized and typed
|
||||
- keybindings runtime tests with fake watch source plus one real watcher integration test
|
||||
- Orchestration:
|
||||
- receipt tests proving checkpoint refs and projections are complete before completion signals resolve
|
||||
- replacement of polling-based checkpoint/integration waits with receipt-based waits
|
||||
- Web:
|
||||
- transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state
|
||||
- Validation gate:
|
||||
- `bun run lint`
|
||||
- `bun run typecheck`
|
||||
- `mise exec -- bun run test`
|
||||
- repeated full-suite run after cutover to confirm flake removal
|
||||
|
||||
## Assumptions and Defaults
|
||||
- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral.
|
||||
- No backward-compatibility layer is required for old websocket push envelopes.
|
||||
- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism.
|
||||
- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local.
|
||||
@@ -0,0 +1,823 @@
|
||||
# Server Auth Model Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
|
||||
|
||||
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
|
||||
|
||||
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
|
||||
|
||||
## Primary goals
|
||||
|
||||
- Make auth server-wide, not WebSocket-only.
|
||||
- Make insecure exposure hard to do accidentally.
|
||||
- Preserve zero-login local desktop UX for desktop-managed environments.
|
||||
- Support browser-native pairing and session auth.
|
||||
- Leave room for native/mobile credentials later without rewriting the server boundary.
|
||||
- Keep auth separate from transport and launch method.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Full multi-user authorization and RBAC.
|
||||
- OAuth / SSO / enterprise identity.
|
||||
- Passkeys or biometric UX in v1.
|
||||
- Syncing auth state across environments.
|
||||
- Designing the full remote environment product in this document.
|
||||
|
||||
## Core decisions
|
||||
|
||||
### 1. Auth is a server concern
|
||||
|
||||
Every privileged surface of the T3 server must go through the same auth policy engine:
|
||||
|
||||
- HTTP routes
|
||||
- WebSocket upgrades
|
||||
- RPC methods reached through WebSocket
|
||||
|
||||
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
|
||||
|
||||
### 2. Pairing and session are different things
|
||||
|
||||
The system should distinguish:
|
||||
|
||||
- bootstrap credentials
|
||||
- session credentials
|
||||
|
||||
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
|
||||
|
||||
Session credentials are the durable credentials used after pairing.
|
||||
|
||||
Bootstrap should never become the long-lived request credential.
|
||||
|
||||
### 3. Auth and transport are separate
|
||||
|
||||
Auth must not be defined by how the client reached the server.
|
||||
|
||||
Examples:
|
||||
|
||||
- local desktop-managed server
|
||||
- LAN `ws://`
|
||||
- public `wss://`
|
||||
- tunneled `wss://`
|
||||
- SSH-forwarded `ws://127.0.0.1:<port>`
|
||||
|
||||
All of these should feed into the same auth model.
|
||||
|
||||
### 4. Exposure level changes defaults
|
||||
|
||||
The more exposed an environment is, the narrower the safe default should be.
|
||||
|
||||
Safe default expectations:
|
||||
|
||||
- local desktop-managed: auto-pair allowed
|
||||
- loopback browser access: explicit bootstrap allowed
|
||||
- non-loopback bind: auth required
|
||||
- tunnel/public endpoint: auth required, explicit enablement required
|
||||
|
||||
### 5. Browser and native clients may use different session credentials
|
||||
|
||||
The auth model should support more than one session credential type even if only one ships first.
|
||||
|
||||
Examples:
|
||||
|
||||
- browser session cookie
|
||||
- native bearer/device token
|
||||
|
||||
This should be represented in the model now, even if browser cookies are the first implementation.
|
||||
|
||||
## Target auth domain
|
||||
|
||||
### Route classes
|
||||
|
||||
Every route or transport entrypoint should be classified as one of:
|
||||
|
||||
1. `public`
|
||||
2. `bootstrap`
|
||||
3. `authenticated`
|
||||
|
||||
#### `public`
|
||||
|
||||
Unauthenticated by definition.
|
||||
|
||||
Should be extremely small. Examples:
|
||||
|
||||
- static shell needed to render the pairing/login UI
|
||||
- favicon/assets required for the pairing screen
|
||||
- a minimal server health/version endpoint if needed
|
||||
|
||||
#### `bootstrap`
|
||||
|
||||
Used only to exchange a bootstrap credential for a session.
|
||||
|
||||
Examples:
|
||||
|
||||
- Initial bootstrap envelope over file descriptor at startup
|
||||
- `POST /api/auth/bootstrap`
|
||||
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
|
||||
|
||||
#### `authenticated`
|
||||
|
||||
Everything that reveals machine state or mutates it.
|
||||
|
||||
Examples:
|
||||
|
||||
- WebSocket upgrade
|
||||
- orchestration snapshot and events
|
||||
- terminal open/write/close
|
||||
- project search and file writes
|
||||
- git routes
|
||||
- attachments
|
||||
- project favicon lookup
|
||||
- server settings
|
||||
|
||||
The default stance should be: if it touches the machine, it is authenticated.
|
||||
|
||||
## Credential model
|
||||
|
||||
### Bootstrap credentials
|
||||
|
||||
Initial credential types to model:
|
||||
|
||||
- `desktop-bootstrap`
|
||||
- `one-time-token`
|
||||
|
||||
Possible future credential types:
|
||||
|
||||
- `device-code`
|
||||
- `passkey-assertion`
|
||||
- `external-identity`
|
||||
|
||||
#### `desktop-bootstrap`
|
||||
|
||||
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
|
||||
|
||||
Properties:
|
||||
|
||||
- launcher-provided
|
||||
- short-lived
|
||||
- one-time or bounded-use
|
||||
- never shown to the user as a reusable password
|
||||
|
||||
#### `one-time-token`
|
||||
|
||||
Used for explicit browser/mobile pairing flows.
|
||||
|
||||
Properties:
|
||||
|
||||
- short TTL
|
||||
- one-time use
|
||||
- safe to embed in a pairing URL fragment
|
||||
- exchanged for a session credential
|
||||
|
||||
### Session credentials
|
||||
|
||||
Initial credential types to model:
|
||||
|
||||
- `browser-session-cookie`
|
||||
- `bearer-session-token`
|
||||
|
||||
#### `browser-session-cookie`
|
||||
|
||||
Primary browser credential.
|
||||
|
||||
Properties:
|
||||
|
||||
- signed
|
||||
- `HttpOnly`
|
||||
- bounded lifetime
|
||||
- revocable by server key rotation or session invalidation
|
||||
|
||||
#### `bearer-session-token`
|
||||
|
||||
Reserved for native/mobile or non-browser clients.
|
||||
|
||||
Properties:
|
||||
|
||||
- opaque token, not a bootstrap secret
|
||||
- long enough lifetime to survive reconnects
|
||||
- stored in secure client storage when available
|
||||
|
||||
## Auth policy model
|
||||
|
||||
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
|
||||
|
||||
### Policy examples
|
||||
|
||||
#### `DesktopManagedLocalPolicy`
|
||||
|
||||
Default for desktop-managed local server.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `desktop-bootstrap`
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
|
||||
Disabled by default:
|
||||
|
||||
- `one-time-token`
|
||||
- `bearer-session-token`
|
||||
- password login
|
||||
- public pairing
|
||||
|
||||
#### `LoopbackBrowserPolicy`
|
||||
|
||||
Used for browser access on localhost without desktop-managed bootstrap.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `one-time-token`
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
|
||||
#### `RemoteReachablePolicy`
|
||||
|
||||
Used when binding non-loopback or using an explicit remote/tunnel workflow.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `one-time-token`
|
||||
- possibly `desktop-bootstrap` when a desktop shell is brokering access
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
- `bearer-session-token`
|
||||
|
||||
#### `UnsafeNoAuthPolicy`
|
||||
|
||||
Should exist only as an explicit escape hatch.
|
||||
|
||||
Requirements:
|
||||
|
||||
- explicit opt-in flag
|
||||
- loud startup warnings
|
||||
- never defaulted automatically
|
||||
|
||||
## Effect-native service model
|
||||
|
||||
### `ServerAuth`
|
||||
|
||||
The main auth facade used by HTTP routes and WebSocket upgrade handling.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- classify requests
|
||||
- authenticate requests
|
||||
- authorize bootstrap attempts
|
||||
- create sessions from bootstrap credentials
|
||||
- enforce policy by environment mode
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface ServerAuthShape {
|
||||
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
routeClass: RouteAuthClass,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
input: BootstrapExchangeInput,
|
||||
) => Effect.Effect<SessionGrant, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/ServerAuth",
|
||||
) {}
|
||||
```
|
||||
|
||||
### `BootstrapCredentialService`
|
||||
|
||||
Owns issuance, storage, validation, and consumption of bootstrap credentials.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- issue desktop bootstrap grants
|
||||
- issue one-time pairing tokens
|
||||
- validate TTL and single-use semantics
|
||||
- consume bootstrap grants atomically
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface BootstrapCredentialServiceShape {
|
||||
readonly issueDesktopBootstrap: (
|
||||
input: IssueDesktopBootstrapInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly issueOneTimeToken: (
|
||||
input: IssueOneTimeTokenInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly consume: (
|
||||
presented: PresentedBootstrapCredential,
|
||||
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `SessionCredentialService`
|
||||
|
||||
Owns creation and validation of authenticated sessions.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- mint cookie sessions
|
||||
- mint bearer sessions
|
||||
- validate active session credentials
|
||||
- revoke sessions if needed later
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface SessionCredentialServiceShape {
|
||||
readonly createBrowserSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
|
||||
readonly createBearerSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
|
||||
readonly authenticateCookie: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
readonly authenticateBearer: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `ServerAuthPolicy`
|
||||
|
||||
Pure policy/config service that decides which credential types are allowed.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- map runtime mode and bind/exposure settings to allowed auth methods
|
||||
- answer whether a route can be public
|
||||
- answer whether remote exposure requires auth
|
||||
|
||||
This should stay mostly pure and cheap to test.
|
||||
|
||||
### `ServerSecretStore`
|
||||
|
||||
Owns long-lived server signing keys and secrets.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- get or create signing key
|
||||
- rotate signing key
|
||||
- abstract secure OS-backed storage vs filesystem fallback
|
||||
|
||||
Important:
|
||||
|
||||
- prefer platform secure storage when available
|
||||
- support hardened filesystem fallback for headless/server-only environments
|
||||
|
||||
### `BrowserSessionCookieCodec`
|
||||
|
||||
Focused utility service for cookie encode/decode/signing behavior.
|
||||
|
||||
This should not own policy. It should only own the cookie format.
|
||||
|
||||
### `AuthRouteGuards`
|
||||
|
||||
Thin helper layer used by routes to enforce auth consistently.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- require auth for HTTP route handlers
|
||||
- classify route auth mode
|
||||
- convert auth failures into `401` / `403`
|
||||
|
||||
This prevents every route from re-implementing the same pattern.
|
||||
|
||||
Integrates with `HttpRouter.middleware` to enforce auth consistently.
|
||||
|
||||
## Suggested layer graph
|
||||
|
||||
```text
|
||||
ServerSecretStore
|
||||
├─> BootstrapCredentialService
|
||||
├─> BrowserSessionCookieCodec
|
||||
└─> SessionCredentialService
|
||||
|
||||
ServerAuthPolicy
|
||||
├─> BootstrapCredentialService
|
||||
├─> SessionCredentialService
|
||||
└─> ServerAuth
|
||||
|
||||
ServerAuth
|
||||
└─> AuthRouteGuards
|
||||
```
|
||||
|
||||
Layer naming should follow existing repo style:
|
||||
|
||||
- `ServerSecretStoreLive`
|
||||
- `BootstrapCredentialServiceLive`
|
||||
- `SessionCredentialServiceLive`
|
||||
- `ServerAuthPolicyLive`
|
||||
- `ServerAuthLive`
|
||||
- `AuthRouteGuardsLive`
|
||||
|
||||
## High-level implementation examples
|
||||
|
||||
### Example: WebSocket upgrade auth
|
||||
|
||||
Current state:
|
||||
|
||||
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
|
||||
|
||||
Target shape:
|
||||
|
||||
```ts
|
||||
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
yield* serverAuth.authenticateWebSocketUpgrade(request);
|
||||
return yield* httpApp;
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Then the `/ws` route becomes:
|
||||
|
||||
```ts
|
||||
export const websocketRpcRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
rpcWebSocketHttpEffect.pipe(
|
||||
websocketUpgradeAuth,
|
||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
|
||||
|
||||
### Example: authenticated HTTP route
|
||||
|
||||
For routes like attachments or project favicon:
|
||||
|
||||
```ts
|
||||
const authenticatedRoute = (routeClass: RouteAuthClass) =>
|
||||
HttpMiddleware.make((httpApp) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
yield* serverAuth.authenticateHttpRequest(request, routeClass);
|
||||
return yield* httpApp;
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```ts
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
||||
serveAttachment.pipe(
|
||||
authenticatedRoute(RouteAuthClass.Authenticated),
|
||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
### Example: desktop bootstrap exchange
|
||||
|
||||
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
|
||||
|
||||
That grant is then exchanged for a browser cookie session when the renderer loads.
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
const pairDesktopRenderer = Effect.gen(function* () {
|
||||
const bootstrapService = yield* BootstrapCredentialService;
|
||||
const credential = yield* bootstrapService.issueDesktopBootstrap({
|
||||
audience: "desktop-renderer",
|
||||
ttlMs: 30_000,
|
||||
});
|
||||
return credential;
|
||||
});
|
||||
```
|
||||
|
||||
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
|
||||
|
||||
### Example: one-time pairing URL
|
||||
|
||||
For browser-driven pairing:
|
||||
|
||||
```ts
|
||||
const createPairingToken = Effect.gen(function* () {
|
||||
const bootstrapService = yield* BootstrapCredentialService;
|
||||
return yield* bootstrapService.issueOneTimeToken({
|
||||
ttlMs: 5 * 60_000,
|
||||
audience: "browser",
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
|
||||
|
||||
## Sequence diagrams
|
||||
|
||||
These flows are meant to anchor the auth model in concrete user journeys.
|
||||
|
||||
The important invariant across all of them is:
|
||||
|
||||
- access method is not the auth method
|
||||
- launch method is not the auth method
|
||||
- bootstrap credential is not the session credential
|
||||
|
||||
### Normal desktop user
|
||||
|
||||
This is the default desktop-managed local flow.
|
||||
|
||||
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopMain = Electron main
|
||||
SecretStore = secure local secret backend
|
||||
T3Server = local backend child process
|
||||
Frontend = desktop renderer
|
||||
|
||||
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
|
||||
SecretStore --> DesktopMain : signing key available
|
||||
|
||||
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
|
||||
DesktopMain -> T3Server : send desktop bootstrap envelope
|
||||
note over T3Server : policy = DesktopManagedLocalPolicy
|
||||
note over T3Server : allowed pairing = desktop-bootstrap only
|
||||
|
||||
Frontend -> DesktopMain : request local bootstrap grant
|
||||
DesktopMain --> Frontend : short-lived desktop bootstrap grant
|
||||
|
||||
Frontend -> T3Server : POST /api/auth/bootstrap
|
||||
T3Server -> T3Server : validate desktop bootstrap grant
|
||||
T3Server -> T3Server : create browser session
|
||||
T3Server --> Frontend : Set-Cookie: session=...
|
||||
|
||||
Frontend -> T3Server : GET /ws + authenticated cookie
|
||||
T3Server -> T3Server : validate cookie session
|
||||
T3Server --> Frontend : websocket accepted
|
||||
```
|
||||
|
||||
### `npx t3` user
|
||||
|
||||
This is the standalone local server flow.
|
||||
|
||||
There is no trusted desktop shell here, so pairing should be explicit.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
UserShell = npx t3 launcher
|
||||
T3Server = standalone local server
|
||||
Browser = browser tab
|
||||
|
||||
UserShell -> T3Server : start server
|
||||
T3Server -> T3Server : getOrCreate("server-signing-key")
|
||||
note over T3Server : policy = LoopbackBrowserPolicy
|
||||
|
||||
UserShell -> T3Server : issue one-time pairing token
|
||||
T3Server --> UserShell : pairing URL or pairing token
|
||||
|
||||
UserShell --> Browser : open /pair?token=...
|
||||
|
||||
Browser -> T3Server : GET /pair?token=...
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create browser session
|
||||
T3Server --> Browser : Set-Cookie: session=...
|
||||
T3Server --> Browser : redirect to app
|
||||
|
||||
Browser -> T3Server : GET /ws + authenticated cookie
|
||||
T3Server --> Browser : websocket accepted
|
||||
```
|
||||
|
||||
### Phone user with tunneled host
|
||||
|
||||
This is the explicit remote access flow for a browser on another device.
|
||||
|
||||
The tunnel only provides reachability. It must not imply trust.
|
||||
|
||||
Recommended UX:
|
||||
|
||||
- desktop shows a QR code
|
||||
- desktop also shows a copyable pairing URL
|
||||
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = user at the host machine
|
||||
DesktopMain = desktop app
|
||||
Tunnel = tunnel provider
|
||||
T3Server = T3 server
|
||||
PhoneBrowser = mobile browser
|
||||
|
||||
DesktopUser -> DesktopMain : enable remote access via tunnel
|
||||
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
|
||||
DesktopMain -> Tunnel : publish local T3 endpoint
|
||||
Tunnel --> DesktopMain : public https/wss URL
|
||||
|
||||
DesktopMain -> T3Server : issue one-time pairing token
|
||||
T3Server --> DesktopMain : pairing token
|
||||
DesktopMain -> DesktopUser : show QR code / shareable URL
|
||||
|
||||
DesktopUser -> PhoneBrowser : scan QR / open URL
|
||||
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
|
||||
Tunnel -> T3Server : forward request
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create mobile browser session
|
||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
||||
T3Server --> PhoneBrowser : redirect to app
|
||||
|
||||
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
|
||||
Tunnel -> T3Server : forward websocket upgrade
|
||||
T3Server --> PhoneBrowser : websocket accepted
|
||||
```
|
||||
|
||||
### Phone user with private network
|
||||
|
||||
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
|
||||
|
||||
The auth flow should stay the same.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = user at the host machine
|
||||
T3Server = T3 server
|
||||
PrivateNet = tailscale / private LAN
|
||||
PhoneBrowser = mobile browser
|
||||
|
||||
DesktopUser -> T3Server : enable private-network access
|
||||
T3Server -> T3Server : switch policy to RemoteReachablePolicy
|
||||
DesktopUser -> T3Server : issue one-time pairing token
|
||||
T3Server --> DesktopUser : pairing URL / QR
|
||||
|
||||
DesktopUser -> PhoneBrowser : open private-network URL
|
||||
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
|
||||
PrivateNet -> T3Server : route request
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create mobile browser session
|
||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
||||
T3Server --> PhoneBrowser : redirect to app
|
||||
|
||||
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
|
||||
PrivateNet -> T3Server : websocket upgrade
|
||||
T3Server --> PhoneBrowser : websocket accepted
|
||||
```
|
||||
|
||||
### Desktop user adding new SSH hosts
|
||||
|
||||
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
|
||||
|
||||
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = local desktop user
|
||||
DesktopMain = desktop app
|
||||
SSH = ssh transport/session
|
||||
RemoteHost = remote machine
|
||||
RemoteT3 = remote T3 server
|
||||
Frontend = desktop renderer
|
||||
|
||||
DesktopUser -> DesktopMain : add SSH host
|
||||
DesktopMain -> SSH : connect to remote host
|
||||
SSH -> RemoteHost : probe environment / verify t3 availability
|
||||
DesktopMain -> SSH : run remote launch command
|
||||
SSH -> RemoteHost : t3 remote launch --json
|
||||
RemoteHost -> RemoteT3 : start or reuse server
|
||||
RemoteT3 --> RemoteHost : port + environment metadata
|
||||
RemoteHost --> SSH : launch result JSON
|
||||
SSH --> DesktopMain : remote server details
|
||||
|
||||
DesktopMain -> SSH : establish local port forward
|
||||
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
|
||||
|
||||
note over RemoteT3 : policy = RemoteReachablePolicy
|
||||
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
|
||||
|
||||
Frontend -> DesktopMain : request bootstrap for selected environment
|
||||
DesktopMain --> Frontend : short-lived bootstrap grant
|
||||
|
||||
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
|
||||
RemoteT3 -> RemoteT3 : validate bootstrap grant
|
||||
RemoteT3 -> RemoteT3 : create browser session
|
||||
RemoteT3 --> Frontend : Set-Cookie: session=...
|
||||
|
||||
Frontend -> RemoteT3 : GET /ws + authenticated cookie
|
||||
RemoteT3 --> Frontend : websocket accepted
|
||||
```
|
||||
|
||||
## Storage decisions
|
||||
|
||||
### Server secrets
|
||||
|
||||
Use a `ServerSecretStore` abstraction.
|
||||
|
||||
Preferred order (use a layer for each, resolve on startup):
|
||||
|
||||
1. OS secure storage if available
|
||||
2. hardened filesystem fallback if not
|
||||
|
||||
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
|
||||
|
||||
### Client credentials
|
||||
|
||||
Client-side credential persistence should prefer secure storage when available:
|
||||
|
||||
- desktop: OS keychain / secure store
|
||||
- mobile: platform secure storage
|
||||
- browser: cookie session for browser auth
|
||||
|
||||
This concern should stay in the client shell/runtime layer, not the server auth layer.
|
||||
|
||||
## What to build now
|
||||
|
||||
These are the parts worth building before remote environments ship:
|
||||
|
||||
1. `ServerAuth` service boundary.
|
||||
2. route classification and route guards.
|
||||
3. `ServerSecretStore` abstraction.
|
||||
4. bootstrap vs session credential split.
|
||||
5. browser session cookie codec as one session method.
|
||||
6. explicit auth capabilities/config surfaced in contracts.
|
||||
|
||||
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
|
||||
|
||||
## What to add as part of first remote-capable auth
|
||||
|
||||
1. Browser pairing flow using one-time bootstrap token and cookie session.
|
||||
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
|
||||
3. Auth-required defaults for any non-loopback or explicitly published server.
|
||||
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
|
||||
|
||||
## What to defer
|
||||
|
||||
- passkeys / WebAuthn
|
||||
- iCloud Keychain / Face ID-specific UX
|
||||
- multi-user permissions
|
||||
- collaboration roles
|
||||
- OAuth / SSO
|
||||
- polished session management UI
|
||||
- complex device approval flows
|
||||
|
||||
These can all sit on top of the same bootstrap/session/service split.
|
||||
|
||||
## Relationship to future remote environments
|
||||
|
||||
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
|
||||
|
||||
Keep the design focused on:
|
||||
|
||||
- one T3 server
|
||||
- one auth policy
|
||||
- multiple credential types
|
||||
- multiple future access methods
|
||||
|
||||
That keeps the server auth model stable even as access methods expand later.
|
||||
|
||||
## Recommended implementation order
|
||||
|
||||
### Phase 1
|
||||
|
||||
- Introduce route auth classes.
|
||||
- Add `ServerAuth` and `AuthRouteGuards`.
|
||||
- Move existing `authToken` check behind `ServerAuth`.
|
||||
- Require auth for all privileged HTTP routes as well as WebSocket.
|
||||
|
||||
### Phase 2
|
||||
|
||||
- Add `ServerSecretStore` service with platform-specific layer implementations.
|
||||
- `layerOSXKeychain`, `layer
|
||||
- Add bootstrap/session split.
|
||||
- Add browser session cookie support.
|
||||
- Add one-time bootstrap exchange endpoint.
|
||||
|
||||
### Phase 3
|
||||
|
||||
- Add desktop bootstrap flow on top of the same services.
|
||||
- Make desktop-managed local environments default to bootstrap-only pairing.
|
||||
- Surface auth capabilities in shared contracts and renderer bootstrap.
|
||||
|
||||
### Phase 4
|
||||
|
||||
- Add non-browser bearer session support if mobile/native needs it.
|
||||
- Add richer policy modes for remote-reachable environments.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- No privileged HTTP or WebSocket path bypasses auth policy.
|
||||
- Local desktop-managed flows still avoid a visible login screen.
|
||||
- Non-loopback or published environments require explicit authenticated pairing by default.
|
||||
- Bootstrap and session credentials are distinct in code and in behavior.
|
||||
- Auth logic is centralized in Effect services/layers rather than route-local branching.
|
||||
@@ -0,0 +1,349 @@
|
||||
# Remote Endpoints and Hosted Static App Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Make remote access feel first-class while keeping the free DIY path open.
|
||||
|
||||
The immediate product goal is:
|
||||
|
||||
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
|
||||
- users can generate a hosted pairing link for `app.t3.codes`
|
||||
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
|
||||
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
|
||||
|
||||
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
|
||||
|
||||
## Current State
|
||||
|
||||
Already present or in progress:
|
||||
|
||||
- Server auth distinguishes bootstrap credentials from session credentials.
|
||||
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
|
||||
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
|
||||
- Remote environment WebSocket connections use a short-lived WebSocket token.
|
||||
- Pairing URLs can carry tokens in the URL fragment.
|
||||
- Hosted `/pair?host=...#token=...` can add a saved environment.
|
||||
- Hosted static startup can avoid assuming the page origin is the backend.
|
||||
|
||||
Main gaps:
|
||||
|
||||
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
|
||||
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
|
||||
- Tailscale/MagicDNS endpoints are not detected or surfaced.
|
||||
- Hosted-static empty/offline states are still thin.
|
||||
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
|
||||
|
||||
## Core Decision: Add `AdvertisedEndpoint`
|
||||
|
||||
Add a new first-class contract instead of extending the environment descriptor.
|
||||
|
||||
### Why not extend `ExecutionEnvironmentDescriptor`
|
||||
|
||||
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
|
||||
|
||||
Examples:
|
||||
|
||||
- environment id
|
||||
- label
|
||||
- platform
|
||||
- server version
|
||||
- capabilities
|
||||
|
||||
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
|
||||
|
||||
Examples:
|
||||
|
||||
- loopback URL
|
||||
- LAN URL
|
||||
- Tailscale IP URL
|
||||
- MagicDNS/Serve URL
|
||||
- manual URL
|
||||
- future T3 Tunnel URL
|
||||
- browser compatibility and exposure level
|
||||
|
||||
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
|
||||
|
||||
### Target Contract
|
||||
|
||||
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
|
||||
|
||||
```ts
|
||||
type AdvertisedEndpointProvider =
|
||||
| "loopback"
|
||||
| "lan"
|
||||
| "tailscale-ip"
|
||||
| "tailscale-magicdns"
|
||||
| "manual"
|
||||
| "t3-tunnel";
|
||||
|
||||
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
|
||||
|
||||
type AdvertisedEndpointCompatibility = {
|
||||
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
|
||||
desktopApp: "compatible" | "unknown";
|
||||
};
|
||||
|
||||
type AdvertisedEndpoint = {
|
||||
id: string;
|
||||
provider: AdvertisedEndpointProvider;
|
||||
label: string;
|
||||
httpBaseUrl: string;
|
||||
wsBaseUrl: string;
|
||||
visibility: AdvertisedEndpointVisibility;
|
||||
compatibility: AdvertisedEndpointCompatibility;
|
||||
source: "server" | "desktop" | "user";
|
||||
status: "available" | "unavailable" | "unknown";
|
||||
isDefault?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
|
||||
|
||||
## HTTP/WS and HTTPS/WSS Readiness
|
||||
|
||||
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
|
||||
|
||||
What is ready:
|
||||
|
||||
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
|
||||
- Saved environments store both HTTP and WebSocket base URLs.
|
||||
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
|
||||
- WebSocket connections can use a dynamically issued `wsToken`.
|
||||
- Server CORS support exists for browser remote auth endpoints.
|
||||
|
||||
What is not solved by code alone:
|
||||
|
||||
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
|
||||
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
|
||||
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
|
||||
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
|
||||
|
||||
Policy:
|
||||
|
||||
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
|
||||
- Mark endpoint compatibility at the product layer.
|
||||
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Endpoint Sources
|
||||
|
||||
Endpoint records can come from several providers:
|
||||
|
||||
1. **Server runtime**
|
||||
- headless bind host and port
|
||||
- server-known explicit advertised host config
|
||||
|
||||
2. **Desktop shell**
|
||||
- loopback backend URL
|
||||
- LAN exposure state
|
||||
- network interface discovery
|
||||
- Tailscale CLI/status discovery
|
||||
|
||||
3. **User configuration**
|
||||
- manually added hostnames
|
||||
- preferred endpoint labels
|
||||
- hidden/disabled endpoints
|
||||
|
||||
4. **Future cloud provider**
|
||||
- T3 Tunnel endpoint
|
||||
- billing/account status
|
||||
- tunnel lifecycle state
|
||||
|
||||
### Endpoint Registry
|
||||
|
||||
Create a central runtime registry:
|
||||
|
||||
- `packages/contracts/src/remoteAccess.ts`
|
||||
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
|
||||
- `apps/server/src/remoteAccess/*` for server/headless endpoints
|
||||
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
|
||||
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
|
||||
|
||||
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
|
||||
|
||||
### Pairing Link Generation
|
||||
|
||||
Move hosted pairing link generation to endpoint-driven input:
|
||||
|
||||
```ts
|
||||
buildHostedPairingUrl({
|
||||
endpoint: AdvertisedEndpoint,
|
||||
token,
|
||||
});
|
||||
```
|
||||
|
||||
Generated URL:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
|
||||
```
|
||||
|
||||
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
|
||||
|
||||
## Phase 1: Endpoint Abstraction
|
||||
|
||||
### Goals
|
||||
|
||||
- Centralize URL normalization, protocol derivation, and compatibility checks.
|
||||
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
|
||||
- Preserve all current remote behavior.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
|
||||
2. Add shared helpers:
|
||||
- normalize HTTP base URL
|
||||
- derive WebSocket base URL
|
||||
- classify loopback/private/LAN/Tailscale/public host
|
||||
- classify hosted HTTPS compatibility
|
||||
3. Add server endpoint discovery:
|
||||
- loopback endpoint
|
||||
- configured non-loopback endpoint
|
||||
- explicit advertised host override
|
||||
4. Add desktop endpoint discovery:
|
||||
- local loopback
|
||||
- LAN exposure endpoint
|
||||
- endpoint status labels
|
||||
5. Add WebSocket/API method or existing config field for endpoint snapshots.
|
||||
6. Refactor settings connections UI:
|
||||
- render endpoint rows
|
||||
- endpoint picker for pairing link copy
|
||||
- show compatibility warnings
|
||||
7. Refactor hosted link builder to accept endpoint records.
|
||||
8. Add tests for URL normalization and compatibility classification.
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- Existing LAN/network access UI still works.
|
||||
- Pairing links are generated from endpoint records.
|
||||
- Loopback endpoints never produce hosted pairing links silently.
|
||||
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
|
||||
- No remote environment runtime changes are required for existing saved environments.
|
||||
|
||||
## Phase 2: BYO Tailscale/MagicDNS
|
||||
|
||||
### Goals
|
||||
|
||||
- Detect free DIY Tailscale reachability.
|
||||
- Surface Tailscale endpoints as normal advertised endpoints.
|
||||
- Keep users in control of their own tailnet.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Detect Tailscale IPs from network interfaces:
|
||||
- IPv4 `100.64.0.0/10`
|
||||
- mark as `provider: "tailscale-ip"`
|
||||
2. Add optional desktop-side `tailscale status --json` discovery:
|
||||
- MagicDNS hostname
|
||||
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
|
||||
- graceful failure if CLI is missing
|
||||
3. Add manual Tailscale endpoint override:
|
||||
- hostname
|
||||
- label
|
||||
- preferred/default flag
|
||||
4. Show Tailscale endpoint rows in settings:
|
||||
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
|
||||
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
|
||||
5. Generate pairing links using selected Tailscale endpoint.
|
||||
6. Document DIY setup:
|
||||
- local desktop-to-desktop over Tailscale
|
||||
- hosted app requirements
|
||||
- why HTTPS matters
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- A machine on Tailscale shows a Tailscale endpoint without paid features.
|
||||
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
|
||||
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
|
||||
- Tailscale is optional and never required for regular LAN/loopback use.
|
||||
|
||||
## Phase 3: Hosted Static App Completion
|
||||
|
||||
### Goals
|
||||
|
||||
- `app.t3.codes` works as a real client shell.
|
||||
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Finish hosted-static root behavior:
|
||||
- no primary backend required
|
||||
- saved environment hydration before initial routing decisions
|
||||
- first saved environment selected as active
|
||||
2. Add hosted empty state:
|
||||
- no saved environments
|
||||
- paste pairing URL
|
||||
- add host + token
|
||||
3. Add offline saved environment UI:
|
||||
- last connected
|
||||
- reconnect
|
||||
- remove
|
||||
- copy/add alternate endpoint
|
||||
4. Audit primary-backend assumptions:
|
||||
- command palette
|
||||
- settings pages
|
||||
- server config atom defaults
|
||||
- keybindings
|
||||
- provider/model lists
|
||||
- update/desktop-only affordances
|
||||
5. Add route tests for:
|
||||
- hosted `/pair?host=...#token=...`
|
||||
- hosted root with no saved environments
|
||||
- hosted root with saved environment
|
||||
- primary backend unavailable but saved environment present
|
||||
6. Add deployment hardening:
|
||||
- SPA fallback
|
||||
- strict CSP
|
||||
- no third-party scripts
|
||||
- no query token logging
|
||||
- disable or hide source maps in production if needed
|
||||
7. Add browser error messages:
|
||||
- mixed content
|
||||
- unreachable backend
|
||||
- CORS failure
|
||||
- certificate failure
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
|
||||
- A saved environment can be used without any backend at `app.t3.codes`.
|
||||
- Offline machines show a useful state instead of a generic boot error.
|
||||
- HTTP endpoints are still supported in desktop/native/local contexts.
|
||||
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
|
||||
|
||||
## Phase 4: Future T3 Tunnel Provider
|
||||
|
||||
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
|
||||
|
||||
Future tunnel provider responsibilities:
|
||||
|
||||
- create endpoint with `provider: "t3-tunnel"`
|
||||
- surface tunnel status
|
||||
- provide stable HTTPS URL
|
||||
- use existing backend pairing/session auth
|
||||
- never bypass server auth
|
||||
|
||||
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- Pairing tokens are short-lived and one-time.
|
||||
- Generated hosted pairing links put tokens in the fragment.
|
||||
- The backend remains the authorization boundary.
|
||||
- Endpoint discovery never disables backend auth.
|
||||
- Hosted app does not silently downgrade to HTTP.
|
||||
- Tunnel/public endpoints require explicit user action.
|
||||
- Client sessions remain revocable.
|
||||
- Endpoint URLs and request logs must avoid recording pairing tokens.
|
||||
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
|
||||
|
||||
## Verification
|
||||
|
||||
Each implementation PR should run:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- focused tests for changed backend/web behavior
|
||||
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
|
||||
@@ -0,0 +1,246 @@
|
||||
# Plan: Thread Lineage And Lazy Context Transfer
|
||||
|
||||
## Summary
|
||||
|
||||
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
|
||||
|
||||
Architecture reference: `docs/orchestration-v2/thread-lineage-and-context-transfer.md`.
|
||||
|
||||
## Goals
|
||||
|
||||
- Support user-created fork threads for exploration.
|
||||
- Keep fork creation provider-neutral and cheap.
|
||||
- Reuse the same source-point/context-transfer model for provider switching, merge-back, and future subagents.
|
||||
- Prefer native same-provider fork at first dispatch when available.
|
||||
- Fall back to portable context only when native transfer is unavailable or target provider differs.
|
||||
- Keep all behavior replayable through V2 events/projections.
|
||||
|
||||
## Non-Goals For First Slice
|
||||
|
||||
- Full portable context generation quality.
|
||||
- Cross-provider adapter implementation beyond the data/runtime hook.
|
||||
- Merge-back UI.
|
||||
- Native or custom subagent orchestration.
|
||||
- Forking from actively streaming provider state.
|
||||
- Backward compatibility with old dev databases.
|
||||
|
||||
## Core Data Model
|
||||
|
||||
Add schema/contracts for:
|
||||
|
||||
```ts
|
||||
type ContextTransferType =
|
||||
| "fork"
|
||||
| "provider_handoff"
|
||||
| "merge_back"
|
||||
| "subagent_spawn"
|
||||
| "subagent_result";
|
||||
|
||||
type ContextSourcePoint = {
|
||||
threadId: ThreadId;
|
||||
runId?: RunId;
|
||||
checkpointId?: CheckpointId;
|
||||
turnItemId?: TurnItemId;
|
||||
providerThreadRef?: NativeThreadRef;
|
||||
providerTurnRef?: NativeTurnRef;
|
||||
};
|
||||
|
||||
type ContextTransferStatus =
|
||||
| "pending"
|
||||
| "resolved_native"
|
||||
| "resolved_portable"
|
||||
| "failed"
|
||||
| "consumed"
|
||||
| "superseded";
|
||||
```
|
||||
|
||||
Persist:
|
||||
|
||||
- `orchestration_v2_projection_context_transfers`
|
||||
- optional later portable handoff payload columns/table if the existing context handoff projection is not enough
|
||||
|
||||
For the first slice, `ContextTransfer` is required. Materialized `ContextHandoff` payloads can be deferred until portable context is implemented.
|
||||
|
||||
## Events
|
||||
|
||||
Add V2 events:
|
||||
|
||||
- `context-transfer.created`
|
||||
- `context-transfer.updated`
|
||||
- possibly `context-handoff.created` later
|
||||
|
||||
Do not emit provider-native fork details as app identity. Native fork refs belong in the transfer resolution payload and provider thread refs.
|
||||
|
||||
## Commands
|
||||
|
||||
Add:
|
||||
|
||||
```ts
|
||||
type ThreadForkCommand = {
|
||||
type: "thread.fork";
|
||||
commandId: CommandId;
|
||||
sourceThreadId: ThreadId;
|
||||
targetThreadId: ThreadId;
|
||||
sourcePoint:
|
||||
| { type: "latest_stable" }
|
||||
| { type: "run"; runId: RunId }
|
||||
| { type: "checkpoint"; checkpointId: CheckpointId };
|
||||
title?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
```
|
||||
|
||||
First-slice policy:
|
||||
|
||||
- `latest_stable` resolves to latest completed run checkpoint.
|
||||
- explicit completed run/checkpoint is accepted.
|
||||
- active run source is rejected or resolved to latest stable checkpoint; choose one policy and test it.
|
||||
- target thread starts idle.
|
||||
- no provider session/thread is created by `thread.fork`.
|
||||
|
||||
## Runtime Hook
|
||||
|
||||
Add a provider-neutral start-context resolver used by run startup:
|
||||
|
||||
```ts
|
||||
resolveStartContext({
|
||||
threadId,
|
||||
runId,
|
||||
provider,
|
||||
modelSelection,
|
||||
userMessage,
|
||||
}): Effect<StartContextResolution, StartContextResolutionError>
|
||||
```
|
||||
|
||||
Resolution order:
|
||||
|
||||
1. No pending transfer targeting the thread/run: normal run start.
|
||||
2. Pending fork transfer and same provider with native fork support: resolve native fork.
|
||||
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
|
||||
4. Failed resolution: fail command before provider side effects.
|
||||
|
||||
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
|
||||
|
||||
## Codex Native Fork Path
|
||||
|
||||
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
|
||||
|
||||
Implementation target:
|
||||
|
||||
- use native fork only when source provider is Codex and source native refs are strong;
|
||||
- create or bind a new `ProviderThread` for the forked native thread;
|
||||
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
|
||||
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
|
||||
- preserve source app thread lineage separately from native thread refs.
|
||||
|
||||
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
|
||||
|
||||
## Portable Context Fallback
|
||||
|
||||
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
|
||||
|
||||
Minimum viable fallback:
|
||||
|
||||
- detect cross-provider fork/handoff need;
|
||||
- create failed/unsupported transfer resolution with a clear command error, or
|
||||
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
|
||||
|
||||
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
|
||||
|
||||
## Merge-Back Preparation
|
||||
|
||||
Do not implement merge-back in the first slice, but keep model support:
|
||||
|
||||
- `ContextTransfer.type = "merge_back"`
|
||||
- `basePoint` on transfer
|
||||
- source thread may differ from target thread
|
||||
|
||||
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
|
||||
|
||||
## Subagent Preparation
|
||||
|
||||
Do not implement subagents in this slice, but keep model support:
|
||||
|
||||
- `createdBy: "agent"`
|
||||
- `type: "subagent_spawn"` and `"subagent_result"`
|
||||
- source/target thread relationship fields
|
||||
|
||||
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
|
||||
|
||||
## Projection And Debugger
|
||||
|
||||
Backend projection first:
|
||||
|
||||
- expose thread lineage in thread projection;
|
||||
- expose context transfers in debug projection;
|
||||
- expose transfer status and resolution strategy.
|
||||
|
||||
Debugger after backend:
|
||||
|
||||
- fork button/control from stable source point;
|
||||
- show thread lineage/source point;
|
||||
- show pending/resolved/failed transfers;
|
||||
- show native vs portable resolution.
|
||||
|
||||
Do not build debugger controls before the backend projection is authoritative.
|
||||
|
||||
## Tests
|
||||
|
||||
Use `bun run test`, not `bun test`.
|
||||
|
||||
Required backend tests:
|
||||
|
||||
- `thread.fork` from latest completed checkpoint creates target thread and pending transfer.
|
||||
- fork command is idempotent through command receipts.
|
||||
- fork does not create provider session/thread eagerly.
|
||||
- first run on same-provider fork invokes native resolution path when capability exists.
|
||||
- unsupported native fork falls back or fails according to explicit policy.
|
||||
- active-run fork policy is deterministic.
|
||||
- replay/recovery preserves target thread lineage and pending transfer.
|
||||
|
||||
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Add contract schemas and ids for context transfers/source points.
|
||||
2. Add migration/projection table for context transfers.
|
||||
3. Add event store/projection handling for transfer events.
|
||||
4. Add `thread.fork` command policy and orchestrator path.
|
||||
5. Add tests for cheap idle fork creation and recovery.
|
||||
6. Add start-context resolver interface.
|
||||
7. Wire resolver into run startup with no-op behavior.
|
||||
8. Add Codex native fork capability investigation and adapter path.
|
||||
9. Add tests for same-provider native fork resolution.
|
||||
10. Add debug projection surface after backend behavior is stable.
|
||||
|
||||
## Validation
|
||||
|
||||
Before considering the slice complete:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- targeted backend tests with `bun run test`
|
||||
|
||||
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
|
||||
|
||||
## Implementation Status
|
||||
|
||||
Implemented in this slice:
|
||||
|
||||
- context transfer ids, schemas, JSON codecs, events, and projection storage
|
||||
- app-thread lineage on thread creation and fork creation
|
||||
- `thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
|
||||
- cheap idle fork creation with no eager provider session/thread/run
|
||||
- Codex same-provider native `thread/fork` resolution on first target dispatch
|
||||
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
|
||||
- transfer status progression through `pending`, `resolved_native`, and `consumed`
|
||||
- command receipt idempotency for duplicate fork commands
|
||||
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
|
||||
|
||||
Explicitly deferred:
|
||||
|
||||
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
|
||||
- merge-back command/runtime
|
||||
- subagent spawn/result runtime
|
||||
- debugger controls for creating/inspecting transfers
|
||||
@@ -0,0 +1,216 @@
|
||||
# Version Control Phase 1: VCS Driver Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
|
||||
|
||||
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
|
||||
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
|
||||
- Add server services under `apps/server/src/vcs`:
|
||||
- `Services/VcsDriver.ts`
|
||||
- `Services/VcsRepositoryResolver.ts`
|
||||
- `Services/VcsProcess.ts`
|
||||
- `Layers/GitVcsDriver.ts`
|
||||
- `errors.ts`
|
||||
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
|
||||
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
|
||||
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
|
||||
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
|
||||
- No T3 Review implementation yet.
|
||||
- No broad UI redesign.
|
||||
|
||||
## Driver Model
|
||||
|
||||
Use provider-neutral nouns in new APIs:
|
||||
|
||||
- `VcsDriver`: local repository mechanics.
|
||||
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
|
||||
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
|
||||
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
|
||||
- `RefName`: branch, bookmark, tag, or provider-specific ref.
|
||||
|
||||
The initial driver capabilities should be explicit:
|
||||
|
||||
```ts
|
||||
export interface VcsDriverCapabilities {
|
||||
readonly kind: "git" | "jj" | "sapling" | "unknown";
|
||||
readonly supportsWorktrees: boolean;
|
||||
readonly supportsBookmarks: boolean;
|
||||
readonly supportsAtomicSnapshot: boolean;
|
||||
readonly supportsPushDefaultRemote: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
|
||||
|
||||
- `detectRepository(cwd)`
|
||||
- `status(cwd, options)`
|
||||
- `listRefs(cwd, query/pagination)`
|
||||
- `checkoutRef(cwd, ref)`
|
||||
- `createRef(cwd, ref, from?)`
|
||||
- `createWorkspace(cwd, ref, path?)`
|
||||
- `removeWorkspace(path)`
|
||||
- `prepareChangeContext(cwd, filePaths?)`
|
||||
- `createChange(cwd, message, options)`
|
||||
- `push(cwd, target?)`
|
||||
- `rangeContext(cwd, base, head)`
|
||||
- `listWorkspaceFiles(cwd, options)`
|
||||
|
||||
## Effect Process Layer
|
||||
|
||||
Create a small reusable `VcsProcess` service instead of using `runProcess`.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
|
||||
- Support scoped acquisition/release for long-running commands and interruption.
|
||||
- Support bounded stdout/stderr collection with truncation markers.
|
||||
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
|
||||
- Support stdin.
|
||||
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
|
||||
- Stream output lines to progress callbacks as Effects.
|
||||
- Return a typed `ProcessOutput` value for successful execution.
|
||||
- Fail with typed errors, not generic thrown exceptions.
|
||||
|
||||
Errors should be schema-backed tagged classes, for example:
|
||||
|
||||
- `VcsProcessSpawnError`
|
||||
- `VcsProcessExitError`
|
||||
- `VcsProcessTimeoutError`
|
||||
- `VcsOutputDecodeError`
|
||||
- `VcsRepositoryDetectionError`
|
||||
- `VcsUnsupportedOperationError`
|
||||
|
||||
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
|
||||
|
||||
## Git Driver Rewrite
|
||||
|
||||
Rewrite Git support against `VcsProcess`.
|
||||
|
||||
Carry forward current behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.test.ts`
|
||||
- current Git status/branch/worktree contracts
|
||||
|
||||
But split the implementation into smaller modules:
|
||||
|
||||
- command execution and hardening config
|
||||
- repository detection
|
||||
- status parsing
|
||||
- branch/ref parsing
|
||||
- worktree operations
|
||||
- commit/range context generation
|
||||
- push/pull operations
|
||||
|
||||
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
|
||||
|
||||
## Freshness and Local Caching
|
||||
|
||||
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
|
||||
|
||||
Treat these as live/local:
|
||||
|
||||
- repository detection for the active cwd
|
||||
- working copy dirty state
|
||||
- staged/unstaged/untracked file summaries
|
||||
- current branch/bookmark/change name
|
||||
- local branch/bookmark lists
|
||||
- local worktree/workspace lists
|
||||
|
||||
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
|
||||
|
||||
Treat these as cached or explicit-refresh only:
|
||||
|
||||
- remote tracking branch refreshes
|
||||
- ahead/behind counts that require network fetches
|
||||
- default branch discovery from a remote provider
|
||||
- remote branch lists beyond locally known refs
|
||||
|
||||
The VCS driver should expose freshness metadata with status results:
|
||||
|
||||
```ts
|
||||
export interface VcsFreshness {
|
||||
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
|
||||
|
||||
Use Effect `Cache` for repository identity and expensive local metadata:
|
||||
|
||||
- key by resolved repository root plus VCS kind
|
||||
- invalidate on cwd/root changes and workspace mutation operations
|
||||
- use short TTLs for local status caches when filesystem events are unavailable
|
||||
- never hide command failures behind stale values unless the caller explicitly accepts stale data
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
Prefer direct migration and deletion over compatibility wrappers.
|
||||
|
||||
Rules:
|
||||
|
||||
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
|
||||
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
|
||||
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
|
||||
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
|
||||
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
|
||||
- No new feature work may depend on transitional modules.
|
||||
|
||||
Expected transitional candidates:
|
||||
|
||||
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
|
||||
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
|
||||
|
||||
## Tests
|
||||
|
||||
Add integration-style tests with real temporary Git repositories for the new Git driver:
|
||||
|
||||
- non-repository detection
|
||||
- status for clean/dirty/untracked/staged states
|
||||
- branch/ref list with pagination
|
||||
- checkout/create branch
|
||||
- worktree create/remove
|
||||
- commit context generation with file filters
|
||||
- commit creation with hook progress events
|
||||
- push behavior against a local bare remote
|
||||
- status polling does not perform remote network refresh by default
|
||||
- concurrent duplicate status requests are coalesced
|
||||
- bounded output/truncation
|
||||
- timeout/interruption
|
||||
- typed error shape for command failure and missing executable
|
||||
|
||||
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `vcs` contracts and tagged errors.
|
||||
2. Add `VcsProcess` and unit tests around process execution semantics.
|
||||
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
|
||||
4. Implement `GitVcsDriver` with real Git command integration tests.
|
||||
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
|
||||
6. Move commit/range/push callers to the VCS service directly.
|
||||
7. Delete migrated `GitCore` internals and tests as each caller group moves.
|
||||
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
|
||||
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Current Git branch/status/worktree/commit behavior remains intact.
|
||||
- New Git implementation does not depend on `processRunner.ts`.
|
||||
- New errors are typed and inspectable by tests.
|
||||
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
|
||||
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Background status refresh is local-only by default and cannot hit provider rate limits.
|
||||
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -0,0 +1,268 @@
|
||||
# Version Control Phase 2: Source Control Provider Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
|
||||
|
||||
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
|
||||
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
|
||||
- Add server services under `apps/server/src/sourceControl`:
|
||||
- `Services/SourceControlProvider.ts`
|
||||
- `Services/SourceControlProviderRegistry.ts`
|
||||
- `Services/SourceControlProcess.ts`
|
||||
- `Layers/GitHubSourceControlProvider.ts`
|
||||
- `errors.ts`
|
||||
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
|
||||
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
|
||||
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
|
||||
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
|
||||
- No in-app review UI yet.
|
||||
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
|
||||
|
||||
## Provider Model
|
||||
|
||||
Use provider-neutral names:
|
||||
|
||||
- `SourceControlProvider`: hosted repository and change-request mechanics.
|
||||
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
|
||||
- `ChangeRequestThread`: review or discussion thread.
|
||||
- `ChangeRequestComment`: top-level or inline comment.
|
||||
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
|
||||
|
||||
Core provider operations:
|
||||
|
||||
- `detectRemote(remoteUrl)`
|
||||
- `checkAuth(cwd)`
|
||||
- `getRepository(cwd | remoteUrl)`
|
||||
- `getDefaultTargetRef(repository)`
|
||||
- `listChangeRequests(repository, filters)`
|
||||
- `getChangeRequest(repository, reference)`
|
||||
- `createChangeRequest(repository, input)`
|
||||
- `checkoutChangeRequest(cwd, changeRequest, options)`
|
||||
- `getCloneUrls(repository)`
|
||||
|
||||
Review-facing operations should be designed now, even if unimplemented:
|
||||
|
||||
- `listReviewThreads(changeRequest)`
|
||||
- `createReviewComment(changeRequest, input)`
|
||||
- `replyToReviewThread(thread, input)`
|
||||
- `resolveReviewThread(thread)`
|
||||
- `submitReview(changeRequest, input)`
|
||||
|
||||
Each operation should be guarded by capabilities:
|
||||
|
||||
```ts
|
||||
export interface SourceControlProviderCapabilities {
|
||||
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
|
||||
readonly supportsCreateChangeRequest: boolean;
|
||||
readonly supportsCheckoutChangeRequest: boolean;
|
||||
readonly supportsReviewThreads: boolean;
|
||||
readonly supportsInlineComments: boolean;
|
||||
readonly supportsDraftChangeRequests: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Provider Registry
|
||||
|
||||
Add a registry that resolves a provider from repository remotes and explicit user input.
|
||||
|
||||
Rules:
|
||||
|
||||
- Detection should be pure where possible and testable without spawning CLIs.
|
||||
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
|
||||
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
|
||||
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
|
||||
|
||||
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
|
||||
|
||||
## Rate Limits and Provider Caching
|
||||
|
||||
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
|
||||
|
||||
Default behavior:
|
||||
|
||||
- Pure URL/remote parsing is always live because it is local.
|
||||
- Provider detection from local remotes is live-local.
|
||||
- Authentication checks are cached.
|
||||
- Repository metadata is cached.
|
||||
- Default branch metadata is cached.
|
||||
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
|
||||
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
|
||||
- Create/update operations invalidate affected cache keys immediately after success.
|
||||
|
||||
The provider API should make freshness explicit:
|
||||
|
||||
```ts
|
||||
export interface SourceControlFreshness {
|
||||
readonly source: "live-local" | "cached-provider" | "live-provider";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
readonly stale?: boolean;
|
||||
}
|
||||
|
||||
export type ProviderRefreshPolicy =
|
||||
| "cache-first"
|
||||
| "stale-while-revalidate"
|
||||
| "force-refresh"
|
||||
| "local-only";
|
||||
```
|
||||
|
||||
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
|
||||
|
||||
Use Effect `Cache` for provider data:
|
||||
|
||||
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
|
||||
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
|
||||
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
|
||||
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
|
||||
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
|
||||
|
||||
Provider drivers should surface rate-limit signals when available:
|
||||
|
||||
- remaining quota
|
||||
- reset time
|
||||
- retry-after duration
|
||||
- whether the limit is primary, secondary/abuse, or unknown
|
||||
|
||||
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
|
||||
|
||||
Avoid rate-limit footguns:
|
||||
|
||||
- no provider calls from render loops or fast status polling
|
||||
- no listing all PRs/MRs across all repos to infer one branch state
|
||||
- no silent GitHub fallback for unknown providers
|
||||
- no unbounded cache cardinality for branch names or free-form search queries
|
||||
- no per-thread duplicate provider refresh when multiple views observe the same repository
|
||||
|
||||
## GitHub Provider Rewrite
|
||||
|
||||
Rewrite GitHub support as `GitHubSourceControlProvider`.
|
||||
|
||||
Carry forward behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitHubCli.ts`
|
||||
- `apps/server/src/git/Layers/GitHubCli.test.ts`
|
||||
- `apps/server/src/git/githubPullRequests.ts`
|
||||
- GitHub-specific `GitManager` PR paths
|
||||
|
||||
Implementation requirements:
|
||||
|
||||
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
|
||||
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
|
||||
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
|
||||
- Keep stdout/stderr bounded.
|
||||
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
|
||||
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
|
||||
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
|
||||
|
||||
## GitManager Cutover
|
||||
|
||||
Refactor `GitManager` so it coordinates three independent services:
|
||||
|
||||
- `VcsDriver` for local repository mechanics.
|
||||
- `SourceControlProviderRegistry` for hosted provider selection.
|
||||
- `TextGeneration` for message/body generation.
|
||||
|
||||
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
|
||||
|
||||
The Commit + PR flow should become:
|
||||
|
||||
1. Resolve VCS repository and local status.
|
||||
2. Resolve source-control provider from remotes.
|
||||
3. Generate commit content through the existing text generation service.
|
||||
4. Create local change through `VcsDriver`.
|
||||
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
|
||||
6. Generate change-request title/body.
|
||||
7. Create the change request through `SourceControlProvider`.
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
This phase should aggressively remove old GitHub-specific internals.
|
||||
|
||||
Rules:
|
||||
|
||||
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
|
||||
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
|
||||
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
|
||||
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
|
||||
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
|
||||
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
|
||||
|
||||
## GitLab and Azure Readiness
|
||||
|
||||
Use the triaged references as implementation inputs, not merge targets:
|
||||
|
||||
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
|
||||
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
|
||||
|
||||
The abstraction should let Phase 3 add:
|
||||
|
||||
- `GitLabSourceControlProvider` using `glab`.
|
||||
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
|
||||
|
||||
No provider should need to edit GitHub code to join the registry.
|
||||
|
||||
## T3 Review Design Constraint
|
||||
|
||||
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
|
||||
|
||||
That means contracts should include stable IDs and enough metadata for:
|
||||
|
||||
- file-level diffs
|
||||
- inline review threads
|
||||
- resolved/unresolved state
|
||||
- top-level discussion comments
|
||||
- pending review submission
|
||||
- provider URL back-links
|
||||
|
||||
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
|
||||
|
||||
## Tests
|
||||
|
||||
Add tests at three levels:
|
||||
|
||||
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
|
||||
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
|
||||
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
|
||||
|
||||
Required cases:
|
||||
|
||||
- GitHub PR URL, number, and branch-ish references.
|
||||
- GitLab MR URL/reference parsing.
|
||||
- Azure DevOps PR URL parsing for same-repo URLs.
|
||||
- unknown provider returns unsupported-operation errors.
|
||||
- missing CLI and auth failures produce distinct typed errors.
|
||||
- invalid CLI JSON fails at decode boundary with useful context.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `sourceControl` contracts and provider-neutral schemas.
|
||||
2. Add shared remote/reference parser helpers and tests.
|
||||
3. Add `SourceControlProcess` and provider errors.
|
||||
4. Add provider registry with GitHub-only registration.
|
||||
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
|
||||
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
|
||||
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
|
||||
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
|
||||
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Existing GitHub Commit + PR and PR checkout flows still work.
|
||||
- `GitManager` no longer imports or depends on `GitHubCli`.
|
||||
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
|
||||
- Unknown/unsupported providers fail explicitly and visibly.
|
||||
- GitHub command execution does not depend on `processRunner.ts`.
|
||||
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
|
||||
- Rate-limit responses become typed errors with retry/reset metadata where available.
|
||||
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,958 @@
|
||||
{
|
||||
"sessionSummaries": [
|
||||
{
|
||||
"sessionKey": "GLOBAL",
|
||||
"summary": "Global cross-thread audit of the v2 orchestrator DB (43,378 events across 63 streams, 6,286 turn items, 60 threads, 206 runs). Core invariants are healthy: event streams have zero version gaps/duplicates and no occurred_at regressions >5s; turn-item ordinals have zero collisions and are 100% consistent with orchestration_v2_turn_item_positions; no nativeItemRef duplicates; outbox (463 rows) and command receipts (580) are fully succeeded/accepted; all 12 failed runs surfaced exactly one user-visible error item; no items/runs stuck beyond the one currently-live run (started 17:03Z, audit ran 17:07Z). Findings are edge-case lineage danglers, generic error strings that discard the underlying cause, sessions left 'ready' after detach, and 13 old local_bash tasks projected as empty-prompt subagents.",
|
||||
"stats": "43,378 events / 63 streams (0 version gaps, 0 dupes, 0 time regressions >5s); 6,286 turn items (6,042 completed, 243 failed, 2 interrupted, 1 running=live); 206 runs (188 completed, 12 failed, 4 cancelled, 1 interrupted, 1 running=live); 212 provider_turns; 19 provider_sessions (3 ready, 16 stopped); 40 subagents (38 completed, 2 failed); outbox 463 rows all 'succeeded'; receipts 580 all 'accepted'; 12 error items total. Loss sample: 258 native tool_use ids in latest 71e29ba5 log \u2192 all accounted for (254 direct items, 3 Agent spawns as subagent items, 1 in-flight run)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "a5a643b2-codex-heya",
|
||||
"summary": "Small 4-run codex smoke session (\"heya\") on 2026-06-28 04:52-05:22 UTC, plus one delegated Claude task child thread. Core pipeline is healthy: all 19 main-thread items + 3 child items are projected with verbatim text, ordinals match turn_item_positions exactly, lineage (run/node/provider_turn refs, subagent -> child thread -> context-transfer -> handoff) fully resolves, and all runs/turns/nodes/items are terminal. Two real problems: the codex-native collab subagent spawned in run 3 left zero trace in ingested events (its wait tool call, web search, and final \"Hello.\" message are lost), and the run-4 delegated Claude task that failed with a 401 auth error is recorded as status \"completed\" everywhere because the adapter ignores is_error on subtype \"success\" results.",
|
||||
"stats": "Main thread: 138 events, 19 projected items (19 distinct item ids in turn-item.updated events), 4 runs / 4 attempts / 4 provider turns, all completed. Child delegated-task thread: 27 events, 3 items, 1 run completed. Native log: 798 lines, 4 turn/start requests but 5 native turns (extra = codex-native subagent thread 019f0c93-d260), 22 item/completed across 2 native threads, 5 reasoning items (all empty summaries), 1 native error (401 auth, is_error:true result)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "a61e9269-codex",
|
||||
"summary": "Short two-turn Codex session (\"hey\" then \"spawn a subagent and say hello\") that spawned one provider-native subagent thread. Pipeline health is very good: every user-visible native item (2 user messages, 2 assistant messages, webSearch, subAgentActivity, child assistant message) is ingested and projected with exact untruncated text; lineage is fully consistent (subagent item childThreadId -> child thread, forkedFrom points back to parent provider-thread/turn, provider_turns map to run_attempts); all runs/turns/nodes/items terminal completed matching the native turn/completed events; ordinals match orchestration_v2_turn_item_positions with no collisions or duplicates and projection order matches native emission order. Only gaps: an (empty) reasoning item and token-usage/rate-limit notifications are dropped by the adapter, which has no handlers for them.",
|
||||
"stats": "Native (decoded, deduped): main thread 2 userMessage, 2 agentMessage, 1 subAgentActivity, 1 webSearch, 1 empty reasoning; child thread 1 agentMessage; 3 native turns all turn/completed; 0 native errors, 2 dev-feature warnings. Ingested: 74 events on main stream (versions 0-73, monotonic), 12 on child stream. Projected: 9 turn_items main (incl 2 synthetic checkpoints + workspace-preparation) + 1 child; 2 runs completed, 2 attempts completed, 3 provider_turns completed, 8 nodes completed; positions table matches item ordinals exactly, no duplicates."
|
||||
},
|
||||
{
|
||||
"sessionKey": "20296b49-grok-tasks",
|
||||
"summary": "Short grok session (2026-06-29 21:46-21:48): user said \"yoo\", then \"spawn some subagents\"; grok ran 3 parallel Task subagents (git state, architecture docs, mobile connection changes) as child threads and summarized. Pipeline health is good: all runs/attempts/provider-turns completed, provider session stopped, lineage intact, no ordinal collisions, no duplicates, no truncation (subagent item result lengths 3721/6274/2647 exactly match child assistant_message lengths). The children's 1319-2711 events vs 2 projected items is EXPECTED: each child has exactly 2 distinct item ids (prompt + result) and the event volume is per-token streaming re-upserts of the result item, not lost items.",
|
||||
"stats": "Main thread: 300 events, 14 turn_items, 2 runs (both completed), 2 run_attempts, 2 provider_turns (completed), 9 subagent.updated events -> 3 subagent rows (completed). Children: 3 threads, 5717 events (1319/2711/1687), 2 items each (6 total, all completed), 6 position rows. Native log: 3702 lines (3694 protocol \u2014 payloads redacted to byteLength/itemCount, 8 request), 2 session/prompt \"failed\" (errorTag Interrupt), no other errors. Integrity: 0 bad run/node/turn/parent refs, 0 ordinal collisions, 0 nativeItemRef dupes, 0 timestamp regressions."
|
||||
},
|
||||
{
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"summary": "Short cursor (glm-5.2) session \"Hello therw!\" with 2 user turns and zero assistant output. The 7-line native log is genuine: the backend child process fatally crashed (Node error originating in @cursor/sdk/dist/esm/index.js) ~0.3s after run 1's run.started, killing the provider mid-turn; a startup reconcile then cancelled run 1. Run 2 (\"what did you just say\") resumed the agent but agent.send rejected 4ms after run.start and was projected as a failed run with only a generic error string; the process crashed again with the same @cursor/sdk fatal error 29s later. Projection internals (ordinals, positions, statuses, lineage forward-links) are consistent and all state is terminal \u2014 the problems are crash handling and error fidelity, not ingestion mechanics.",
|
||||
"stats": "47 events on stream 721fc23c-... (seq 6271-6340, versions 0-46); 7 native log lines (all protocol/decoded, 0 assistant/tool output); 4 turn items (2 user_message, 1 command_execution \"Workspace ready\", 1 error); 2 runs (ordinal 1 cancelled, ordinal 2 failed); 2 messages (both user); 1 provider_turn (cancelled); 0 subagents/handoffs/transfers; 2 backend-child process crashes; 2 startup reconciles."
|
||||
},
|
||||
{
|
||||
"sessionKey": "48663fb7-cursor",
|
||||
"summary": "Thread 48663fb7 is a single \"hello\" message sent to the cursor provider (glm-5.2) at 2026-06-29T21:49:07Z. The provider session opened and acked run.started at 21:49:09.097Z, then the server restarted; a startup runtime-reconcile at 21:49:10.775Z cancelled the run/attempt/provider-turn, idled the provider thread, and stopped the session. Pipeline health is good: no native output was lost (the provider emitted nothing after run.started), lineage and ordinals are consistent, and nothing is stuck in a non-terminal state. The only gap is that the user got no assistant response and no explanation of why the run was cancelled.",
|
||||
"stats": "Native log: 4 decoded protocol lines (agent.open/agent.opened/run.start/run.started), 0 provider output items, 0 errors. Events: 28 (stream_version 0-27, seq 6318-6346 excl. 6340). Projections: 1 run (cancelled), 1 attempt (cancelled), 1 provider_turn (cancelled), 1 node (cancelled), 2 turn_items (both completed), 1 message, 0 subagents, 0 child threads. Provider session: stopped; provider thread: idle."
|
||||
},
|
||||
{
|
||||
"sessionKey": "3029dc85-opencode",
|
||||
"summary": "Opencode chat session \"Hey!\" (2026-06-29 22:02-22:16, idle-reaped 22:46): 7 user turns spawning 5 native opencode subagent sessions, 2 cross-provider delegated claudeAgent tasks (results handed back via context-transfer/handoff), and 3 top-level threads (codex/grok/claude). Pipeline health is very good: all 9 runs/7 attempts/12 provider turns completed, every distinct item id in events has exactly one projection, ordinals match event arrival order with zero collisions or duplicates, lineage (run/node/provider-turn/subagent->child-thread) fully resolves, and the provider session was cleanly stopped after the 30-min idle window. Main issues found are debuggability gaps rather than data loss: the one failed tool call projected no error message (file_search items structurally cannot carry one), file_search outputs are never projected, a placeholder \"pending\" provider_thread row lingers, and the native log itself is payload-redacted so content-level verification is impossible.",
|
||||
"stats": "Native log: 17,198 lines (15,542 part deltas, 723 part updates, 204 message updates, 7 promptAsync, 5 session.created, 12 session.idle; 0 error lines). Events: main 3,335 (1,047 turn-item.updated over 50 distinct items), opencode children 1051/1107/559/241/209, delegated-task children 94/34. Projected items: main 50, opencode children 185, delegated children 23 \u2014 every distinct event item id has exactly one projection (50/90/41/39/8/7 match 1:1). Runs: 7 main + 2 delegated, all completed; 7 attempts completed; 12 provider_turns completed; sessions stopped. 1 failed item (file_search), 0 stuck items, 0 ordinal collisions, 0 dangling run/node/turn/thread refs, 0 nativeItemRef dupes, positions table fully consistent."
|
||||
},
|
||||
{
|
||||
"sessionKey": "9f8d616d-opencode",
|
||||
"summary": "Single-turn opencode session ('hey' -> greeting reply) on 2026-06-29: 1 run, 1 provider turn, ~5s of activity, then 30min of heartbeats until the idle reaper stopped the session. The 100-events/5-items ratio is benign: 25 of the 33 turn-item.updated events are streaming updates of one reasoning part. No data loss, no duplicates, no ordering violations, no errors in the native log, and all runs/turns/items are terminal. Only minor findings: the pending-vs-resolved provider-thread dual-row pattern leaves run/attempt/turn pointing at a different provider_thread_id than the items, and the resolved provider-thread row lingered 'active' for ~20h after session stop before being marked idle.",
|
||||
"stats": "Native log: 273 lines (180 heartbeats, 32 file.watcher, 31 part deltas, 7 part updates, 6 message updates, 1 session.idle, 0 errors). Ingested: 100 events (stream_version 0-99 contiguous, 100 distinct event_ids), incl. 33 turn-item.updated over exactly 5 distinct items. Projected: 5 turn_items (ordinals 1000001-1000005, positions table matches 1:1), 2 messages, 1 run + 1 attempt + 1 provider_turn (all completed), 3 nodes completed, 2 checkpoints, 0 subagents/children, provider_session stopped."
|
||||
},
|
||||
{
|
||||
"sessionKey": "1156181e-delegated-task",
|
||||
"summary": "MCP delegated task \"hello-opus-48\" sent one user prompt (\"Say hello briefly and stop.\") to claudeAgent (claude-opus-4-8). The API call never succeeded: the SDK logged two api_retry events with error_status 401 (authentication_failed) and then emitted a synthetic assistant message \"Failed to authenticate. API Error: 401 Invalid authentication credentials\" plus a result with subtype \"success\" but is_error:true / api_error_status:401. Ingestion and projection are structurally clean (all 3 items projected, ordinals consistent, lineage valid, nothing stuck), but the run/attempt/provider-turn were all recorded as \"completed\" with no failure info, so the delegated task looks successful despite executing zero tokens.",
|
||||
"stats": "Native log: 10 decoded lines (1 query.open, 1 prompt.offer, 5 system incl. 2x api_retry 401, 1 synthetic assistant msg, 1 result is_error:true). Events: 30 (stream_version 0-29, sequences 116-168). Projections: 1 run, 1 attempt, 1 provider_turn, 2 messages, 3 turn_items (user_message, assistant_message, checkpoint), 0 child threads/subagents. Errors seen: 401 authentication_failed x3."
|
||||
},
|
||||
{
|
||||
"sessionKey": "6d618dc4-mcp-group",
|
||||
"summary": "MCP-driven fan-out session: 2 claudeAgent delegated-task threads plus 3 parallel MCP threads (codex :0, grok :1, claudeAgent :2), all single-run. Pipeline health is good overall: all 122 items verified against native logs with exact tool-call counts (19/19 on :2, 1/1 and 16/16 on the delegated tasks), ordinals fully consistent with turn_item_positions, zero lineage orphans, no duplicates, and the codex 400 model error was ingested verbatim and surfaced as a user-visible failed error item. Main defects found: the claudeAgent adapter (as of the code that ran, fc23be8184) concatenates intra-turn assistant text segments without separators into one end-of-turn item, destroying segment boundaries and native interleaving; and the three claudeAgent provider sessions were never idle-reaped, staying 'ready' for ~21 hours until a simultaneous shutdown sweep.",
|
||||
"stats": "5 threads, 1842 ingested events (34/94/22/1587/105), 122 projected items (4/19/2/75/22), 5 runs (4 completed, 1 failed), 5 provider turns, 5 provider sessions (all stopped). Native: mcp log 3763 lines (grok 3158 / claude 499 / codex 106), delegated log 495 lines. 1 provider error (codex 400), 0 orphan run/node/provider_turn/parent references, 0 ordinal collisions, 0 nativeItemRef dupes, positions match 122/122."
|
||||
},
|
||||
{
|
||||
"sessionKey": "5dcea72d-grok-subagent",
|
||||
"summary": "Two-run grok session (\"spawn a subagent\"): run 1 asked the user clarifying questions (xai-question), spawned a background explore subagent; run 2 fetched its output via a blocking TaskOutput tool call and summarized it. Main-thread projections are complete and consistent (16 items, all completed, positions/ordinals match, no dupes, all terminal states correct, no backwards timestamps). The main problem is the subagent child thread: it froze at spawn time with a placeholder result, and the subagent's entire live transcript (116 tool calls over 74.9s) was never ingested \u2014 the real output survives only inside a parent-thread tool item.",
|
||||
"stats": "Native log: 7028 lines, 3501 decoded incoming + 8 decoded outgoing protocol msgs, 10 request events (2 session/prompt terminations logged failed/Interrupt); payload contents are redacted (shape-only). Ingested: 257 events on main thread + 8 on child thread. Projected: 16 turn_items main + 2 child; 2 runs / 2 attempts / 2 provider_turns all completed; provider session stopped; provider thread idle; 1 subagent row (completed). 0 tool failures / rate limits observed."
|
||||
},
|
||||
{
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks",
|
||||
"summary": "Dev session on scheduled tasks: run 1 on codex, then a provider handoff to claudeAgent for runs 2-10 (8 completed, run 9 user-cancelled, run 10 failed 2s after query.open with no SDK response). Pipeline health is very good: zero lost native content in the claudeAgent portion, lineage fully intact, ordering matches native emission exactly, no duplicates, and nothing stuck non-terminal (session stopped, provider threads idle, 0 running items). The only real defect found is that run 10's failure was persisted with a hardcoded generic message, making it undebuggable from the DB.",
|
||||
"stats": "Main thread: 1707 events, 363 items (169 codex run-1 + 194 claude), 69 messages, 10 runs, 10 provider turns (8 completed/1 cancelled/1 failed). 15 child threads: 2 Explore subagents (95+245 events, 20+50 items) + 13 bash-task threads (7-9 events, 2 items each); all child items completed. Native log 5336 lines (2 files, runs 2-10 only). Cross-checks: 156/156 main tool_use ids accounted for (154 toolu items + 2 Agent calls projected as task subagent items), 64/64 subagent tool_use ids, assistant text preserved exactly (27311 chars log = 27311 chars items), 94 thinking blocks all natively empty (SDK sends thinking_delta with empty text), 5/5 is_error tool_results projected as failed, 1 api_retry (recovered), 14 task_notifications + 1 task_updated-only completion (bqu8waxt3) all reconciled; 0 ordinal collisions, 0 position mismatches, 0 orphan lineage refs. All backgrounded-bash tasks completed within their runs, so cross-run/wakeup paths were not exercised in this session."
|
||||
},
|
||||
{
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"summary": "Long claudeAgent coding session (PR #3638 scheduled-tasks work, 20:56-23:43 UTC on 2026-07-01) with 16 runs, 2 Task subagents, and heavy post-turn wakeup activity via task notifications. The persisted portion of the pipeline is healthy \u2014 lineage, ordinals/positions, ordering vs native emission, terminal states, and text fidelity all check out \u2014 but roughly 40% of the provider's actual output (10 full post-turn wakeup turns: 16 assistant messages and ~84 tool calls, including real git pushes) was never ingested at all, this being one of the threads on which that gap was originally diagnosed. Two error-handling gaps stand out: a 401 auth failure projected as a completed run, and run 10's failure persisted only as 'Claude Agent SDK query failed.' with no root cause recorded anywhere.",
|
||||
"stats": "Native log: 8088 lines (all protocol/decoded): 25 results, 594 assistant msgs (68 distinct main-thread text msgs, 122 with thinking), 371 unique tool_use (307 main / 64 child), 49 task_notification, 4 rate_limit (all 'allowed'), 3 query.open, 1 query.close. Ingested: 1546 events on main stream. Projected: 16 runs (15 completed, 1 failed), 16 provider_turns, 308 main items + 70 child items = 378 (positions table matches 378, no collisions/dupes), 68 messages, 2 subagents (both completed, child threads linked). Coverage gap: 84 tool calls + 16 assistant texts in log with no projection (all in wakeup windows); 0 items stuck running/streaming."
|
||||
},
|
||||
{
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"summary": "Long mixed-provider session (13 claudeAgent runs, then a clean claudeAgent\u2192cursor provider handoff at run 14, then 3 failed cursor runs) with two claudeAgent subagent child threads. Core pipeline health is good: ordering/positions are perfectly consistent, no duplicates, no stuck non-terminal items/nodes/messages, sampled long assistant text survives un-truncated, and handoff lineage (context-transfer consumed \u2192 handoff ready \u2192 run 14, thread.provider-switched) is fully intact. The big defect is the known 'invisible post-turn turns' problem: three post-run wakeup turns (10 and 17 native turns' worth of tool calls, including a GitHub comment being posted) produced zero events and zero projections. Secondary issues: 529-Overloaded turns (runs 11-13) projected as completed despite native is_error:true, and cursor run failures persisted with only a generic 'Provider turn failed.' string.",
|
||||
"stats": "Events: 6482 (main) + 165 + 255 (two subagent child threads). Items: 695 main + 34 + 52 child; positions table matches 695/695 with zero ordinal collisions, zero duplicate nativeItemRefs. Runs: 17 total \u2014 13 claudeAgent completed, 1 cursor completed (14), 3 cursor failed (15/16/17; 15 had a superseded steering_restart attempt). 2 subagents, both completed and linked to child threads. Tool-call coverage: cursor run 15 window 51/51 projected; claudeAgent era 529 native tool_use ids, all projected except 42 post-turn-wakeup calls (lost) and 2 Agent spawns (correctly represented as subagent items). Nodes: 751, all terminal. Errors seen natively: 3 is_error results (529 Overloaded), 1 error_during_execution, 1 model_refusal_fallback, 29 api_retry, 3 cursor run status:error."
|
||||
},
|
||||
{
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns",
|
||||
"summary": "Two-run cursor session (composer-2.5, fastMode) where the user asked why cursor turns fail; run 1 completed a full debugging pass, run 2 hung silently for 440s and failed \u2014 reproducing the very bug being investigated. The ingestion/projection pipeline itself is in excellent health: all 123 native tool calls plus reasoning/assistant text project 1:1 with exact character counts (3664/3664 assistant, 3382/3382 thinking), ordering matches native emission exactly, positions table is consistent (150/150, 0 ordinal mismatches or dupes), lineage refs all resolve, no stuck states (run/attempt/turn/node all 'failed' for run 2, session 'stopped' after agent.close), and timestamps are monotonic. The one substantive problem is error-handling fidelity: the run 2 failure is projected only as failure {message:\"Provider turn failed.\", code:null}, because CursorAdapterV2 reads a non-existent result.error and never surfaces the Cursor SDK's real error_code (an authentication error), dropping even the requestId/durationMs present in the decoded payload.",
|
||||
"stats": "Native log: 1920 decoded protocol lines, 2 native runs (run-1cbebefe finished; run-f4d64e64 status error), 123 distinct tool calls (87 shell / 18 read / 14 grep / 4 glob; 118 natively completed), 17 thinking blocks, 3664 assistant chars, 3382 thinking chars. Ingested: 906 orchestration_events for the stream. Projected: 150 turn items (2 user_message, 5 assistant_message, 17 reasoning, 88 command_execution, 36 file_search, 1 checkpoint, 1 error), 2 runs (1 completed / 1 failed), 2 run attempts, 2 provider turns, 7 messages, 0 subagents/child threads. 1 provider failure seen (generic)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "8ee00dcc-cursor-spacing",
|
||||
"summary": "Single-run Cursor (composer-2.5, fastMode) session: user asked to remove extra spacing on the mobile Threads/Home screen; the agent searched, read files, made 3 edits to HomeScreen.tsx, and summarized. The pipeline is essentially clean: every native item (33 tool calls, 10 thinking segments, 3 assistant messages, 1 user message) maps 1:1 to projected turn_items with exact content fidelity, ordinals are contiguous and match native emission order, all statuses reached terminal states, and no errors occurred in the native log. Only minor gaps found: token usage from the native turn-ended/run.completed is not ingested anywhere, and run_attempt.provider_turn_id is never backfilled.",
|
||||
"stats": "Native log: 665 lines (all stage=decoded), 659 interaction.update (33 tool-call-started + 33 tool-call-completed, 10 thinking-completed, 94 text-delta, 107 thinking-delta, 377 token-delta, 3 partial-tool-call, 1 turn-ended, 1 step-completed) + run.start/started/completed + agent.open/opened/close. Events: 415 (stream versions 0-414 contiguous; 194 turn-item.updated, 194 node.updated). Projections: 49 turn_items (1 user_message, 1 workspace-prep command_execution, 3 assistant_message, 10 reasoning, 29 file_search, 3 file_change, 1 tool command_execution, 1 checkpoint), 49 positions, 1 run (completed), 1 attempt (completed), 1 provider_turn (completed), 4 messages. Zero errors in native log."
|
||||
},
|
||||
{
|
||||
"sessionKey": "codex-no-native-logs",
|
||||
"summary": "Four sibling codex threads multiplexed onto the shared codex app-server session ('provider-session:provider-instance:codex:shared'). The missing native logs are explained: the codex protocol logger is bound to the threadId that opened the shared session (71e29ba5, whose own codex native thread is 019f1b50), so all four threads' traffic went to 71e29ba5's log file and was mostly rotated away by that thread's heavy claude traffic. Events-to-projections consistency is excellent: all 11 runs and provider turns terminal (10 completed, 1 user-interrupted with proper interrupt request/result items), zero lineage violations, zero ordinal collisions or duplicates, projection order matches native start order (verified against the surviving log window for c878541b runs 4-6), and message text verified byte-exact (1733/1733 chars). Only gaps: codex reasoning items (empty-content in this session) and one contextCompaction item are not projected at all.",
|
||||
"stats": "4 sibling codex threads (not parent/child; 0 subagent rows), 1797 events total (1077/468/222/30), 11 runs (10 completed, 1 interrupted), 440 turn_items (117 assistant_message, 264 command_execution incl. 20 failed, 18 file_change, 8 dynamic_tool, 12 user_message, 11 checkpoint, 2 interrupt items), 129 messages sampled on c878541b (61 assistant/7 user = item counts). 0 lineage violations, 0 ordinal collisions, 0 native-ref dupes, 0 non-terminal items/runs/turns/nodes. Native log survives only for c878541b runs 4-6 (16:00-16:44Z window)."
|
||||
},
|
||||
{
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"summary": "Largest session in the store: the wakeup/blur dev thread, started on codex (runs 1-55), provider-switched to claudeAgent via a ready context handoff (runs 56-122), spawning 7 claude subagent child threads; still live during the audit (run 122 completed mid-audit at 17:13:36Z). In-run ingestion is very healthy: ordinals/positions are perfectly consistent across main + child threads with zero collisions or dangling lineage refs, projection order exactly matches native emission (run 121 verified item-by-item), no duplicates, no stuck items/turns/streaming messages, and all failed runs and user-interrupted subagents are surfaced with error/failed items. The two significant problems are both loss-of-data outside run windows: 76 completed claudeAgent tool calls plus assistant text from post-turn task_notification wakeup turns were never ingested (the known invisible-post-turn-turns bug this thread was used to develop the fix for \u2014 no provider_wakeup runs exist here), and a 30-minute codex-era ingestion gap (16:10-16:40 Jul 1) lost 119 command/fileChange items with only assistant text later backfilled at a single flattened timestamp.",
|
||||
"stats": "Main thread: 14259 events (seq 13799-43607, still live during audit), 3390 projected turn_items (922 assistant_message, 1658 command_execution, 345 file_change, 144 dynamic_tool, 26 web_search, 7 subagent, 4 error, 169 user_message, 117 checkpoint, 1 handoff), 1091 messages, 122 runs = 122 provider_turns (117 completed / 4 failed / 1 cancelled, statuses exactly aligned). 7 subagent child threads (not 9): 79-260 events and 17-53 items each, 214 child items total. Native logs cover only 2026-07-01T16:00:59Z onward (~50k lines, 11 files; earlier rotations deleted). Claude era: 1130 native toolu ids vs 1045 projected (76 lost in wakeup gaps, 7 Agent-remapped, 2 in-flight). Codex era (in-log): 450 native call ids, 119 unprojected. 4 native error_during_execution, 2 orchestrator transport failures, 1 user cancel, 2 user-interrupted subagents."
|
||||
}
|
||||
],
|
||||
"confirmed": [
|
||||
{
|
||||
"title": "Codex-native collab subagent (run 3) entirely missing from events and projections",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "User prompt run 3 was 'spawn a subagent'. Native log a5a643b2-...log shows: item/completed subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq (kind 'started', agentThreadId 019f0c93-d260-7740-a477-0c0d19e8b299, agentPath /root/hello_agent) at 2026-06-28T04:54:02.530Z; collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX (tool 'wait', inProgress 04:54:04.013Z -> completed 04:54:14.015Z); and on child native thread 019f0c93-d260: webSearch ws_08e14d73aa33777f016a40a8f75cd0819ba433374351c23d4f (query 'Codex OpenAI latest docs'), reasoning rs_08e14..., agentMessage msg_08e14d73aa33777f016a40a8fd816c819bbd856f295f6ce730 (text 'Hello.', completed 04:54:23, child turn 019f0c93-d421 completed 04:54:23.777Z -- AFTER parent run 3 finalized 04:54:15.874Z). SQL: 0 rows in orchestration_events for LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%', '%call_9wPxyaS7ueh1MXl7XJt6zysq%', '%ws_08e14d73%', '%msg_08e14d73%', '%019f0c93-d260%'; orchestration_v2_projection_subagents has only the run-4 delegate-task row. Run 3 projected only user_message + 2 assistant messages + checkpoint; the parent assistant text ('Subagent spawned as /root/hello_agent. It hasn't returned within the short wait window yet.') is the only user-visible trace. Note: current CodexAdapterV2.ts (registerSubagentActivity/registerSubagentThreads, lines ~2815/2986; commits 3b864044c6 2026-06-28 'Adopt userdata-v2 and subagent activity mapping' and 57aa76ac14 2026-06-29) now maps these item types, so the session likely ran a pre-fix build -- but the historical data is unrecoverable and the child agent's post-run-completion output (arrived 8s after parent turn completed) remains a late-arrival hazard.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%' OR payload_json LIKE '%019f0c93-d260%'\" # returns 0; vs grep -c 'subAgentActivity\\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log",
|
||||
"sessionKey": "a5a643b2-codex-heya",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Every evidence point reproduces: the native log contains subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq, collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX, and 29 child-thread (019f0c93-d260) lines including agentMessage msg_08e14d73 (\"Hello.\") at 04:54:23.755Z, while orchestration_events and all projections return 0 rows for every identifier; run 3 projected only user_message + 2 assistant messages + checkpoint, and the subagents table has only the run-4 delegate-task row. The child output also arrived 8s after run 3's projected completed_at (04:54:15.874Z), matching the late-arrival claim. So the data loss is real and unrecoverable. Severity adjusted to medium because the session predates fix commit 3b864044c6 (2026-06-28 17:58 PDT, ~20h after the session) and current CodexAdapterV2.ts (lines 2815/2986-2998) now maps both item types, so recurrence for these types is addressed; only the historical loss and an unverified late-arrival hazard remain."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Backend child process fatally crashed twice on @cursor/sdk, killing run 1 mid-turn with no user-visible error",
|
||||
"category": "error-handling",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "server-child.log (~/.t3/userdata-v2/logs/server-child.log): stderr fatal-error dump referencing 'file:///Applications/T3 Code (Alpha).app/.../node_modules/@cursor/sdk/dist/esm/index.js:1' at 2026-06-29T21:48:20.166Z (0.33s after native run.started run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 at 21:48:19.834Z) and again at 21:49:09.455Z (followed by 'Node.js v24.15.0' crash footer). Server restart at 21:48:21.35 logged 'V2 orchestration recovery completed { terminalizedRuns: 1, stoppedSessions: 2 }'. Reconcile events seq 6294-6299 (command:runtime-reconcile:startup...21:48:21.501Z) set run:thread:721fc23c...:ordinal:1, its attempt, and provider-turn run-9d9ff525 to 'cancelled'. Run 1 has no error/cancelled turn item \u2014 user asked 'Hello therw!' and got only the 'Workspace ready' item; the cancellation is silent (run status is the only signal). No assistant content was lost in the log sense (crash preceded any deltas), but the turn was killed by a server bug, not a user cancel, and is projected indistinguishably from a user cancellation.",
|
||||
"repro": "grep -n 'cursor/sdk\\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT event_type,occurred_at FROM orchestration_events WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%'\"",
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Every cited artifact reproduces: the @cursor/sdk fatal stderr dump at 21:48:20.166Z (0.33s after native run.started run-9d9ff525), a second fatal crash at 21:49:09.455Z with Node.js footer and child exit code=1, the recovery log 'terminalizedRuns: 1, stoppedSessions: 2', reconcile events seq 6294-6299 setting run 1/attempt/node/provider-turn to 'cancelled', and no error or cancelled turn item on run 1 (only user_message + workspace item). ProviderRuntimeRecoveryService.ts intentionally marks interrupted runs 'cancelled' and never persists its 'server restarted' detail string user-visibly, so the crash-induced kill is projected identically to a user cancel with zero debuggable trace \u2014 a real gap, though the terminalization itself is designed behavior. Downgraded to medium because recovery worked cleanly (nothing stuck, no assistant content lost since the crash preceded any deltas), and the finding slightly overstates impact: run 2's failure WAS surfaced with a visible provider_error item; only run 1 died silently."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "401 authentication failure recorded as fully successful run \u2014 is_error on SDK result ignored",
|
||||
"category": "error-handling",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log 2026-06-28T05:22:33.360Z: result payload has subtype:\"success\" but is_error:true, api_error_status:401, result:\"Failed to authenticate. API Error: 401 Invalid authentication credentials\", usage all zeros; preceded by two api_retry events (05:22:31.612Z, 05:22:32.312Z, error_status 401 authentication_failed). Projections: run run:...ordinal:1 status=completed (event seq 146, run.updated stream_version 27), run_attempt ...attempt:1 status=completed (seq 139), provider_turn ...attempt%3A1 status=completed (seq 138), assistant turn-item turn-item:provider:claudeAgent:native-item:03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc status=completed. No failure/error field anywhere in any payload_json; the only trace of the error is the synthetic assistant message text (which did survive verbatim, so it is user-visible as ordinary assistant text, not as an error state). Root cause: terminalStatusFromResult in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:1652 returns \"completed\" whenever message.subtype === \"success\" and the failure branch at ~line 3254 only fires for non-success subtypes; is_error/api_error_status are never checked (only tool-result is_error at lines 1498-1500). An MCP delegate_task caller polling run status sees success for a task that never executed.",
|
||||
"repro": "grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-e188-4fe4-8cc5-a294003ebfed-3adel.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';\"",
|
||||
"sessionKey": "1156181e-delegated-task",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Every evidence point reproduces: the native log at 2026-06-28T05:22:33.360Z shows a result with subtype \"success\" but is_error:true, api_error_status:401, zero usage, preceded by two api_retry 401 authentication_failed events (05:22:31.612Z, 05:22:32.312Z); projections show run (seq 146), run_attempt (seq 139), provider_turn (seq 138) and assistant turn-item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc all status=completed with no failure field in any payload_json. The code claim is accurate: terminalStatusFromResult (ClaudeAdapterV2.ts:1658) returns \"completed\" for any subtype===\"success\" and the failure branch at ~3254 only fires for non-success subtypes, while the SDK's SDKResultSuccess type explicitly exposes is_error and api_error_status (sdk.d.ts:2739-2740) \u2014 so this is an ignored error signal, not an SDK ambiguity or intentional design. Severity high stands because this thread is a delegated MCP task whose caller consumes run status programmatically; an auth failure that executed zero turns is reported as a fully successful run, with the only trace being ordinary assistant text."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Subagent live transcript and final output never projected to its child thread",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child thread 'thread:provider:grok:native-thread:019f1b5f-efdb-7da0-acd7-1a31b3fe00bc%3Atask%3Acall-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has only 8 events (sequences 14437-14451, last stream_version 7 at 2026-07-01T01:52:10.705Z) and 2 turn_items, both timestamped at spawn (01:52:10). Its assistant_message item 'turn-item:provider:grok:native-item:call-cdbbacb3-...-1%3Aresult' contains only the bootstrap text 'Subagent started in background... Use get_command_or_subagent_output ... to wait for results.' Yet the task actually ran 01:52:10Z-01:53:25Z with tool_calls=116 (per TaskOutput result in parent item turn-item:provider:grok:native-item:019f1b5f...%3Atool%3Acall-5ca8a4be-6fc8-4924-909c-b198de7dcbc8-2). Native log shows 811 decoded incoming ACP messages between 01:52:14 and 01:52:59 (gap between run 1 Interrupt at 01:52:13.249 and run 2 start at 01:52:59.9) with ZERO orchestration_events ingested for any session stream in that window \u2014 the subagent's streamed activity was dropped, likely because AcpAdapterV2's subagent context (context.subagents / subagentsBySessionId / pendingSubagentNotifications in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts ~line 559) is per-active-turn and turn 1 had already finalized. The 15,053-char final output is preserved un-truncated ONLY inside the parent's turn-2 dynamic_tool item; a user opening the child thread 'Explore codebase structure and architecture' sees none of the subagent's work.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE occurred_at>'2026-07-01T01:52:13.4' AND occurred_at<'2026-07-01T01:52:59' AND (stream_id LIKE '%5dcea72d%' OR stream_id LIKE 'thread:provider:grok:native-thread:019f1b5f%');\" -- returns 0, vs grep of the log showing 811 decoded incoming messages in the same window",
|
||||
"sessionKey": "5dcea72d-grok-subagent",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "All evidence reproduces: child thread has only 8 spawn-time events (seq 14437-14451, all 01:52:10Z) and its result item contains only bootstrap text; 0 orchestration_events exist in the 01:52:13.4-01:52:59 gap despite continuous decoded incoming traffic in the log; run 1 prompt failed with errorTag Interrupt at 01:52:13.249Z and the subagent ran to 01:53:25Z (116 tool_calls per parent TaskOutput item). Code intent confirms this is a bug, not design: AcpAdapterV2's emitSubagentAssistant/projectSubagentNotification/pendingSubagentNotifications (lines 845-882, 1447-1461) are built to stream subagent text into the child thread, but the per-turn context's finalized guard plus run 2's empty subagentsBySessionId map dropped everything; the subagent projection row is also frozen at spawn (completed_at 01:52:10.702Z, result=bootstrap text). Downgraded to medium because the full 15,053-char final output is preserved un-truncated and user-visible in the parent's turn-2 dynamic_tool item, and even happy-path design only projects assistant text chunks (not tool calls) to the child thread \u2014 the loss is the child-thread transcript and an accurate subagent row, not the final answer."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "10 post-turn wakeup turns entirely unpersisted (16 assistant messages + 84 tool calls lost)",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Native log has 25 result messages but only 16 runs exist. 10 results have no corresponding run/message/item: 21:19:42 ('CodeRabbit's final pass came back clean'), 22:14:37, 22:19:27, 22:25:18, 22:32:25, 22:38:55 (review-fix 'Rounds 3-7' incl. real git pushes 'a3c87931a2', 'cb28a0842f', 'c435bec111', '57ca73e655', 'd851eb7b9c'), 23:12:04, 23:17:19, 23:32:05 ('Round 11 pushed c19ceca8a5'), 23:41:55 ('Converged. PR #3638 is fully green'). Diff of tool_use ids in log vs nativeItemRef in projections: 86 missing (84 after excluding 2 Agent ids that are represented as task-id subagent items) \u2014 all timestamped inside wakeup windows (21:19, 22:13-22:38, 22:59:24-32, 23:11:24-34, 23:16-23:23, 23:29-23:31, 23:41). 16 native assistant text messages missing (uuids incl. 6299b5cf-7941-4355-8063-eb9d60d7216f @21:19:41, d226f500-43a0-489e-a1bd-888747c56495 @22:38:54, 093e91b9-0d5b-4ad9-a7a9-2ef06c4c2021 @23:41:52). Zero orchestration_events on the stream between 22:10:30 and 22:48:00 except one provider-session.updated (stopped) at 22:41:50.039Z. No run/message has inputIntent provider_wakeup; all 16 user messages have creationSource=web. This is the documented 'invisible post-turn turns' issue diagnosed on this exact thread (fix implemented later on branch t3code/codex-turn-mapping); this session's data predates the fix.",
|
||||
"repro": "SELECT COUNT(*) FROM orchestration_events WHERE stream_id='47763f5e-76c1-4d67-8037-442a280f1514' AND occurred_at>'2026-07-01T22:10:30' AND occurred_at<'2026-07-01T22:48:00'; -- =1 (session stop only), while the native log shows 5 full result turns in that window: grep '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 | grep 'T22:[123]'",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Every evidence point reproduces: 25 decoded result messages in the native log vs 16 projected runs, with the exact 10 cited orphan results unmatched by any run completed_at; the repro SQL returns 1 (only a provider-session stop at 22:41:50.039Z) for a window where the log shows 5 full turns; 86 top-level tool_use ids (371 in log vs 285 projected across all threads) are missing, all timestamped in the orphan-turn windows; cited assistant texts/uuids exist in the log but in zero projection rows; and no run/message carries provider_wakeup intent. This is real, substantial user-facing data loss (whole review-fix rounds with real git pushes invisible), matching the documented pre-fix \"invisible post-turn turns\" issue on this exact thread \u2014 known issue, but the lost session data is not backfilled by the fix, so high severity stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Invisible post-turn wakeup turns: 42 native tool calls + final assistant messages never ingested or projected",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Three windows where the claudeAgent SDK kept working after the orchestrator closed the run: 23:31:27-23:36:48 (16 calls: Bash/Read/Edit/TaskCreate/TaskUpdate, after run 5 completed 23:30:07), 00:16:13-00:17:13 (9 calls, after run 6 completed 00:16:09), 00:33:32-00:37:24 (16 calls incl. mcp__t3-code__preview_* tools, after run 7 completed 00:33:22). Native results confirm full turns: [2026-07-02T00:17:51.602Z] subtype success num_turns:10 and [00:37:39.534Z] num_turns:17. Zero rows in orchestration_events for e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD (Bash 00:17:05.797Z); zero main-stream events between 00:16:10 and 00:21:50. The wakeup turn's final assistant text 'Done \u2014 comment posted: https://github.com/pingdotgg/t3code/pull/2829#issuecomment-4861082710' (log.2, 00:17:4x) has 0 events and 0 turn_items \u2014 the agent posted a GitHub comment with no user-visible record. This is the diagnosed 'invisible post-turn turns' issue; the fix (turn.wakeup / ProviderWakeupService / attach_wakeup) is on this branch but this session ran on the pre-fix build (this thread is itself the diagnosis session, title 'check in on this thread: 47763f5e...').",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%toolu_012dzkuS4eoKeRiAaQ3icFpD%'\" -- returns 0; grep toolu_012dzkuS4eoKeRiAaQ3icFpD ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2 shows the Bash tool_use",
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Re-ran the full evidence trail: run 5/6/7 completion timestamps match, all 9 window-2 tool ids (e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD) and 33 window-1/3 ids have zero rows in orchestration_events, zero main-stream events exist in all three gap windows, and the final assistant text with the posted GitHub comment URL (issuecomment-4861082710) has 0 events and 0 turn_items despite 4 native log occurrences with a success result (num_turns:10 at 00:17:51.602Z). Minor correction: 5 ids the finding attributed to window 1 belong to run 6 and were ingested, but the total lost count is still exactly 42. The session ran on the pre-fix build (the fix lives uncommitted on this branch), so whole turns including a real-world side effect were permanently lost with no user-visible record \u2014 real lost-data, correctly flagged as a known issue, severity stays high."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Cursor turn failure projected with only generic 'Provider turn failed.' \u2014 real error detail (auth error) never captured",
|
||||
"category": "error-handling",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run 2 (native run-f4d64e64-0af6-42bc-8813-5b6ce53a328d) failed: native log line [2026-07-02T02:35:28.424Z] run.completed result {status:\"error\", requestId:\"beca30c7-7e90-481b-abf7-fdab84b3c48d\", durationMs:440732} \u2014 no error field in the decoded payload, and zero interaction.updates for the entire 440s turn (only run.started at 02:28:07.973Z then silence). Projected error item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...run-f4d64e64... (event seq 38493, occurred_at 2026-07-02T02:35:28.524Z) carries failure {class:\"provider_error\", message:\"Provider turn failed.\", code:null, retryable:null} \u2014 requestId and durationMs from the native payload are dropped too. Cause: CursorAdapterV2.ts:2165-2168 maps `cause: (result as { readonly error?: unknown }).error` which is undefined on the SDK RunResult, falling back to DEFAULT_PROVIDER_FAILURE_MESSAGE. The session's own in-turn diagnosis (final assistant item ...assistant%3Arun-1cbebefe...%3A5) confirmed the real cause lives only in the Cursor SDK store runs.error_code (\"Authentication error If you are logged in, try logging out and back in.\") which T3 never reads. The failure IS surfaced user-visibly (error item status failed, run/attempt/provider-turn all 'failed'), but with zero debuggable detail \u2014 this exact gap forced the user to spawn this debugging thread, and then recurred on the thread itself (run ordinal 2).",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';\" ; grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-4c87-4dd5-b1b6-83834cc73afe.log | tail -1",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Fully reproduced: the projected error item for run-f4d64e64 carries only {\"message\":\"Provider turn failed.\",\"code\":null}, while the native log's run.completed (02:35:28.424Z, status \"error\", requestId beca30c7, durationMs 440732) confirms no detail was captured and requestId/durationMs were dropped. The cited code (CursorAdapterV2.ts:2165-2168) reads (result as {error?: unknown}).error, but @cursor/[email protected]'s RunResult type has no error field whatsoever \u2014 the fallback is guaranteed dead-code behavior for EVERY failed Cursor turn, and the SDK's public store API does expose RunRecord.errorCode (\"Authentication error...\") which T3 never reads. The failure is surfaced user-visibly with correct terminal states (so nothing is swallowed), but the projection retains zero debuggable detail for a systematic, provider-wide failure path, which matches the audit's explicit error-handling criterion; severity high stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Shared codex session native logs written to opener thread's file, not the active thread's \u2014 no log file ever created for these threads",
|
||||
"category": "other",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All four threads bind provider_session_id 'provider-session:provider-instance:codex:shared'. Their codex app-server protocol traffic appears in 71e29ba5-654b-4f67-b363-ad400e5bd016.log.6/.9/.10 (e.g. 019f1b62-f532 = c878541b's nativeThreadRef: 4768 hits in .log.10, 2828 in .log.9), interleaved with that thread's own claudeAgent and codex (019f1b50-4248) traffic. Cause: in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts, codexAppServerClientFactoryFromSettingsLayer.open builds makeCodexAppServerProtocolLogger({ nativeEventLogger, threadId: input.threadId, ... }) once per app-server process; EventNdjsonLogger.write routes to `${threadSegment}.log` from that frozen threadId, so every thread multiplexed onto the shared session logs under the opener's file. No file named c878541b-*/de5f191a-*/68f7595b-*/af66fc2c-* was ever created.",
|
||||
"repro": "grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # hits only 71e29ba5-654b-...log.{6,9,10}, never a file named after the audited threads",
|
||||
"sessionKey": "codex-no-native-logs",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Fully reproduced: all four threads bind provider-session:provider-instance:codex:shared; c878541b's nativeThreadRef 019f1b62-f532 appears exactly 4768x in 71e29ba5.log.10 and 2828x in .log.9 (interleaved with 71e29ba5's own codex ref 019f1b50-4248), and no log file named after any of the four threads exists. Code confirms the cause: CodexAdapterV2.ts line 1136 freezes input.threadId into makeCodexAppServerProtocolLogger at app-server open, so every multiplexed thread's protocol traffic routes to the opener's `${threadSegment}.log` \u2014 defeating EventNdjsonLogger's per-write threadId routing, so this is a misrouting bug, not intent. Downgraded to medium because ingestion/projections for these threads are intact (observability-only defect), though rotation under the busy opener file has permanently deleted 3 of 4 threads' protocol history."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Invisible post-turn wakeup turns (claudeAgent): 76 completed tool calls + assistant text never ingested or projected",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "1130 unique toolu_ ids in decoded native logs vs 1045 projected nativeItemRef ids. Of the 85 unmatched, 7 are Agent spawns (projected under task:<hash>:subagent ids, fine) and 2 are stream-only in-flight blocks; the remaining 76 (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) ALL fall in gaps between run windows \u2014 0 fall inside any run. Example: run 56 completed 2026-07-01T22:18:57.958Z (result subtype=success 22:18:57.333Z); at 22:20:52.374Z 'system task_notification bk7bmoyti' re-woke the session, assistant emitted text 'The build failed \u2014 let me see the actual error.' (22:20:58.275Z) then Bash toolu_011YH7oQm6yGVjWTfxwQ1QsH (22:20:59, tool_result 22:21:00) etc. \u2014 none exist in orchestration_events or turn_items (LIKE search for that text returns 0). This thread has ZERO wakeup runs/messages (0 messages with inputIntent provider_wakeup / creationSource other than agent|provider,user|web), while 367 provider_wakeup events exist elsewhere in the DB (first at 2026-07-01T22:47:41) \u2014 this is the thread on which the fix was being developed (memory: diagnosed 2026-07-01 on threads 47763f5e & 71e29ba5).",
|
||||
"repro": "comm -23 /tmp/native_toolu.txt /tmp/proj_toolu.txt (native ids from grep -h '\"stage\":\"decoded\"' ~/.t3/userdata-v2/logs/provider/71e29ba5-654b-4f67-b363-ad400e5bd016.log* | grep -o 'toolu_[A-Za-z0-9]*' vs SELECT json_extract(payload_json,'$.nativeItemRef.nativeId') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%71e29ba5%')",
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "high",
|
||||
"reasoning": "Re-ran the full evidence trail: 85 genuine claudeAgent tool_use ids in decoded native logs have no projection; after excluding 7 Agent spawns (verified projected as task:<hash> items) and 2 stream-only in-flight blocks, exactly 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) all fall in gaps between run windows (0 inside any of the 127 runs). The cited example reproduces: assistant text 'The build failed...' at 2026-07-01T22:20:58.275Z between run 56 (ended 22:18:57.958Z) and run 57 (started 22:22:38.734Z), with 0 matching rows in orchestration_events; the thread has 0 provider_wakeup events/messages while 367 exist elsewhere. This is the documented known issue the branch fixes, but for this session the provider-emitted tool calls, results, and assistant text are unrecoverably absent from ingestion and projections, with losses continuing into 2026-07-02 \u2014 real high-severity lost data, correctly flagged knownIssue=true."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Provider failures persist only generic error strings; underlying cause is unrecoverable from the DB",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "4 claudeAgent error items say only 'Claude Agent SDK query failed.' (class transport_error, code null) \u2014 e.g. run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:10 failed 2026-07-01T22:48:38 with zero native-log traffic in that minute, so the real exception exists nowhere. Root cause: ClaudeAgentSdkQueryRunnerError.message getter in apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:280 hardcodes the string and discards `cause`. Similarly 4 cursor items say 'Provider turn failed.' (code null) while the native run.completed carried status:'error' plus requestId d1cd7f44-91fb-45ce-bdd3-86e9b5cc8e3e and durationMs 2434335 that were dropped. Counter-example showing it can be done right: codex errors keep full detail ('stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)' and the full 400 invalid_request_error body for gpt-5.3-codex).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT thread_id, json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE type='error';\"",
|
||||
"sessionKey": "GLOBAL",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced the SQL: all 4 claudeAgent error items persist only 'Claude Agent SDK query failed.' (code/retryable null) and no richer detail exists in any orchestration_events row for those failures; the root cause is confirmed at ClaudeAdapterV2.ts:279-281 where the message getter hardcodes the string while the Schema.Defect cause field is discarded by makeProviderFailure (real exception goes only to Effect.logWarning). This is not intentional: ProviderFailure.ts has redaction/4096-char bounding built to persist real error text, and codex failures do persist full detail. Minor correction: the '47763f5e had zero native-log traffic at 22:48' claim is false (8 lines exist in .log.1, outgoing query.open/prompt.offer at 22:48:38.086), and the cursor generic message is partly upstream (native run.completed carried no error message, only requestId d1cd7f44/durationMs which were dropped) \u2014 but the core finding stands, so severity stays medium."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Delegated Claude task failed with 401 auth error but all statuses say 'completed' (is_error ignored on success-subtype result)",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child native log thread-delegated-task-command-3amcp-3a1156181e-...log (2026-06-28T05:22:33Z) shows SDK result {\"type\":\"result\",\"subtype\":\"success\",\"is_error\":true,\"result\":\"Failed to authenticate. API Error: 401 Invalid authentication credentials\"}. Projections: child run run:thread:thread%3Adelegated-task%3Acommand%253Amcp%253A1156181e-...:ordinal:1 status=completed; provider_turn status=completed; subagent row node:delegated-task:command%3Amcp%3A1156181e-...%3Ahello-opus-48 status='completed' with result='Failed to authenticate...'; delegate_task tool item call_qV0wnlB5N6Osa6CPxTGN1Ajh output.status='completed'. Root cause in current code: ClaudeAdapterV2.ts terminalStatusFromResult (~line 1658) returns 'completed' whenever message.subtype==='success' without checking is_error, and the result handler (~line 3254) only attaches a ProviderFailure when subtype!=='success'. Mitigating: the error text IS preserved and user-visible (child assistant item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc text = the 401 message; parent's final assistant message msg_...9bb460 explains the failure), so nothing was swallowed -- but status semantics are wrong for anything filtering on failed tasks.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.result') FROM orchestration_v2_projection_subagents WHERE subagent_id LIKE '%hello-opus-48%'\" # completed | Failed to authenticate. API Error: 401 ...",
|
||||
"sessionKey": "a5a643b2-codex-heya",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Re-ran every evidence step: the child native log shows SDK result subtype=\"success\" with is_error=true and api_error_status=401 (zero tokens, \"Failed to authenticate. API Error: 401...\"), yet the child run, provider_turn, subagent row, and the parent's delegate_task item (call_qV0wnlB5N6Osa6CPxTGN1Ajh, output.status=\"completed\") all report completed. Source confirms the cause: ClaudeAdapterV2.ts terminalStatusFromResult (line 1658) returns \"completed\" on subtype===\"success\" without checking is_error, and the result handler (lines 3250-3263) only attaches a ProviderFailure when subtype!==\"success\" \u2014 is_error is checked only for tool results, so this is an oversight, not intent. Medium stands: the error text is preserved and user-visible, but status semantics are wrong end-to-end for anything filtering on failed delegated tasks."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Streaming deltas persisted as full-row event pairs cause ~2800x event amplification on child result items",
|
||||
"category": "other",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child thread ...composer_call_kFjs8 accumulated 2711 events (1352 turn-item.updated + 1352 message.updated + overhead) to stream a single 6274-char result; the 3 children total 5702 turn-item/message events for ~12.6KB of final text. This one 2-minute session wrote 6017 rows to orchestration_events (43k total table), i.e. each streaming delta is persisted as a full-row upsert event for both the turn item and its message. Not a correctness bug (final projections are correct) but a storage/replay-cost anomaly.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT event_type, COUNT(*) FROM orchestration_events WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;\"",
|
||||
"sessionKey": "20296b49-grok-tasks",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Evidence reproduces exactly: 1352 turn-item.updated + 1352 message.updated events on the single kFjs8 result item with monotonically growing text (4 -> 6274 chars, sequences 2160-4862), and the session totals exactly 6017 event rows. Code confirms the mechanism: AcpAdapterV2.emitSubagentAssistant emits a full-row message+turn-item event pair per agent_message_chunk and ProviderEventIngestor persists each pair durably with no coalescing, throttling, or event-log pruning (ProjectionMaintenance only rebuilds projections by replaying the full log). Quantified: 18.0 MB of payload_json for ~12.6 KB of final subagent text (~1400x, quadratic in output length), 15.5% of the entire event table from one 2-minute session. Final projections are correct so severity stays medium, but the unbounded quadratic storage/replay cost is a real, unmitigated pipeline anomaly, not intended behavior or a misreading."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Run 2 failure projected with generic wrapper message; actual cause dropped from projection and depth-elided in server log",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Error turn item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...ordinal%25253A2... (ordinal 2000002, status failed, 21:48:40.703Z) persists failure = {class:'provider_error', message:'Failed to start run run:thread:721fc23c-2cf3-42bf-9d84-edd94359dca9:ordinal:2 on cursor provider thread provider-thread:provider:cursor:native-thread:pending%3A...', code:null, retryable:null}. That string is ProviderAdapterTurnStartError's message getter (apps/server/src/orchestration-v2/ProviderAdapter.ts:291); RunExecutionService.ts:830 builds the failure via makeProviderFailure({cause: Cause.squash(cause)}) so the tagged error's wrapped `cause` (the real agent.send rejection from CursorAgentSdk runnerError 'run.start') never reaches the projection. The only other record, server-child.log line 89 at 21:48:40.703Z, printed the cause as \"{ _id: 'Cause', failures: [ [Object] ] }\" \u2014 depth-elided. The underlying reason run 2 failed 4ms after run.start is now unrecoverable. Positive: the failure WAS surfaced user-visibly as an error item and run/attempt/node all show 'failed'.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND type='error'\" ; grep -n '721fc23c' ~/.t3/userdata-v2/logs/server-child.log",
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "All cited evidence reproduces: the projected error item and its source event (orchestration_events sequence 6314) both persist only ProviderAdapterTurnStartError's generic message getter (ProviderAdapter.ts:280-293); RunExecutionService.ts:~831 feeds Cause.squash(cause) into makeProviderFailure, which (ProviderFailure.ts:90-113) reads only .message/.code and never unwraps the nested cause defect that CursorAdapterV2.ts:2203 attaches. server-child.log line 89 depth-elides the cause as \"[ [Object] ]\" and the native provider log ends at the outgoing run.start (21:48:40.699Z) with no error event, so the real reason run 2 failed is unrecoverable from any persisted artifact. The failure was surfaced user-visibly with correct terminal statuses, so medium (not high) is the honest severity \u2014 this is a debuggability gap, not silent loss."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Native provider log never records failure frames \u2014 cursor SDK send errors and process death are invisible in the ground-truth log",
|
||||
"category": "other",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log 721fc23c-2cf3-42bf-9d84-edd94359dca9.log ends at [2026-06-29T21:48:40.699Z] with outgoing run.start 'what did you just say' and no incoming frame, though the turn failed at 21:48:40.703Z. In Adapters/CursorAgentSdk.ts send(), the log writes cover outgoing run.start and incoming run.started/interaction.update/run.completed only; when agent.send rejects, Effect.tryPromise raises runnerError(cause,'run.start') with no protocol log write. Similarly run 1 shows run.started at 21:48:19.834Z and then nothing \u2014 no error, no lifecycle/exit record \u2014 because the process crash killed the logger too. Result: the 'ground truth' log cannot explain either failed turn, which is exactly why this session looked suspicious (7 lines vs 47 events).",
|
||||
"repro": "cat ~/.t3/userdata-v2/logs/provider/721fc23c-2cf3-42bf-9d84-edd94359dca9.log | tail -2 ; grep -n 'runnerError(cause, \"run.start\")' apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts",
|
||||
"sessionKey": "721fc23c-cursor",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "low",
|
||||
"reasoning": "Evidence reproduces fully: the native log ends at 21:48:40.699Z with the outgoing run.start and no failure frame while events 6313-6315 record the run failing at 21:48:40.703Z, and CursorAgentSdk.ts's error paths (runnerError catches at lines 408/440; run.completed logged via success-only Effect.tap) confirm no error-frame logging exists \u2014 indeed no adapter has an error/lifecycle log kind at all. However, the pipeline did not swallow anything: the failure was ingested and user-surfaced as turn-item 6314 (type error, status failed) with correct terminal statuses, and the raw cause is logged to the server application log (CursorAdapterV2.ts:2188 logWarning with cause), so this is an observability gap in the debug/protocol log (compounded by the generic projected message with code:null) rather than a data-loss or projection bug. Run 1's \"process crash\" explanation is unproven (DB shows cancelled, lastError null), so I downgrade to low: real, design-wide log-scope limitation worth fixing, but errors remain debuggable and user-visible through other channels."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Failed tool item drops the provider error message (file_search projection has no error/output field)",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Child thread ses_0ea978228: turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc (ordinal 87) went running->failed at 2026-06-29T22:04:02.915Z (events seq 8284 -> 8286 on stream thread:provider:opencode:native-thread:ses_0ea978228ffeVM6qpFUgGn62Vl). Final payload contains only {status:'failed', type:'file_search', pattern:'/Users/julius/Development/Work/codething-mvp/CLAUDE.md'} \u2014 no error text at all. Root cause in OpenCodeAdapterV2.ts: toolOutput() (line 659) returns part.state.error for status 'error', but the file_search branch (~line 1376) only maps 'pattern'; output/error is only attached for dynamic_tool. The contract (packages/contracts/src/orchestrationV2.ts line 841) also has no output/error field on file_search items, so the failure reason is unrecoverable from projections. Failure IS user-visible via status=failed, but not debuggable.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';\"",
|
||||
"sessionKey": "3029dc85-opencode",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced the exact projection payload (failed file_search item prt_f15692f30001qL66As1xsUCQXc, ordinal 87, no error text) and the running->failed transition at events seq 8284->8286. Source confirms the mechanism: OpenCodeAdapterV2.ts toolOutput() (line 659) extracts part.state.error, but the file_search branch (lines 1376-1383) only maps pattern \u2014 output/error is attached only for command_execution/dynamic_tool \u2014 and the contract's file_search schema (orchestrationV2.ts line 841) has no field to hold it. The native log is additionally redacted (protocol payloads logged as fieldCount summaries only), so the error message is unrecoverable anywhere; failure is visible via status=failed but not debuggable, so medium stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Claude assistant text segments merged without separator into a single end-of-turn item, losing interleaving",
|
||||
"category": "lost-data",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Thread :2 native log has 5 assistant text blocks with distinct SDK uuids (341420a1 len 95 @22:09:54, 78f308a1 len 37 @22:09:58, 26b0aa8d len 90 @22:10:11, 31c4bfa0 len 73 @22:11:40, bfa7a134 len 10347 @22:13:07), interleaved with 19 tool calls. Projection has ONE assistant_message item turn-item:provider:claudeAgent:native-item:bfa7a134-04d5-4434-bb14-66927497fb91, ordinal 1000021 (after all tools), text length 10642 = exact sum, joined with no whitespace: '...read all the files thoroughly.I'll read all files in the directory.Let me gather context...'. The 4 intermediate uuids have ZERO orchestration_events (only seq 11544-11546 reference bfa7a134, all at 22:13:07). Root cause in code that ran (git fc23be8184 ClaudeAdapterV2.ts:2815): `context.assistant.text += assistantText.text` with single emission at result time; current worktree code (emitAssistantTextArtifacts per message.uuid) already emits per-segment items, so this appears fixed for future runs.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.text'),80,150) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:2' AND type='assistant_message';\"",
|
||||
"sessionKey": "6d618dc4-mcp-group",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "low",
|
||||
"reasoning": "Reproduced every claim: native log has 5 assistant text blocks (lens 95/37/90/73/10347 at 22:09:54\u201322:13:07) but the projection has one assistant_message item (native ref bfa7a134, ordinal 1000021 after all 19 tools) of length 10642 = exact sum, joined with no separator (\"thoroughly.I'll read all files in the directory.Let me gather context\"); the 4 intermediate uuids have zero orchestration_events while bfa7a134 has seq 11544\u201311547. Historical code (fc23be8184 ClaudeAdapterV2.ts:2815 `context.assistant.text +=`) caused it; current worktree emitAssistantTextArtifacts emits per-nativeItemId, so it is fixed going forward. Real for this session's data, but downgraded to low because no text content was lost (only interleaving/segmentation) and the fix already landed."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Subagent projection marked completed at spawn with placeholder result (lifecycle wrong by ~75s)",
|
||||
"category": "other",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "orchestration_v2_projection_subagents row 'node:provider:grok:native-item:call-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has status=completed, started_at=2026-07-01T01:52:10.677Z, completed_at=2026-07-01T01:52:10.702Z and result='Subagent started in background...\\nUse get_command_or_subagent_output...' \u2014 but the task's real lifetime was 01:52:10Z to 01:53:25Z (duration_secs 74.874 per the TaskOutput payload). The parent 'subagent' turn_item (ordinal 1000007) mirrors the same premature completedAt and placeholder result. Cause visible in AcpAdapterV2.emitSubagent (~lines 1047-1060): when the spawn tool returns 'started in background', taskStatus is non-running and update.result (the bootstrap text) is adopted as assistantText/result; nothing later updates it when the background task actually finishes.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';\"",
|
||||
"sessionKey": "5dcea72d-grok-subagent",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced end-to-end: projection row 'node:provider:grok:native-item:call-cdbbacb3-...-1' has status=completed, completed_at=2026-07-01T01:52:10.702Z with result='Subagent started in background...' while the TaskOutput payload (event seq 14622, 01:53:28.477Z, item call-5ca8a4be-...) shows the task actually ran 01:52:10Z-01:53:25Z (duration_secs 74.874); only 3 subagent.updated events exist, all at spawn time, so nothing ever corrects it. Code confirms the cause: extractXAiAcpSubagentUpdate (XAiAcpExtension.ts:86-91) maps the spawn tool's completed status straight to subagent status with no background-spawn detection, and AcpAdapterV2.ts:1047-1053 adopts the bootstrap text as assistantText/result; the later TaskOutput tool call is projected as an unrelated dynamic_tool item and never routed back to the subagent, and the child thread's only assistant message is also the placeholder. Severity stays medium: the real 15.5KB output survives user-visibly in the separate dynamic_tool item, but the subagent card's lifecycle, result, and child-thread transcript are wrong, and this Grok/ACP path is not covered by the claudeAgent backgrounded-task known issue."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Run 10 terminal failure persisted with only a generic error message",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run run:thread:7f1dfff1-...:ordinal:10 failed at 2026-07-01T20:47:58.607Z. The projected error item (turn-item:provider:claudeAgent:native-item:terminal-failure%3A...ordinal%25253A10..., event seq 25810) has failure {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null, retryable:null}. run-attempt payload (seq 25811) carries no error detail either. Native log ends at 20:47:58.429Z with outgoing query.open + prompt.offer (user text \".\") and zero incoming SDK messages, so the DB retains no clue what actually failed. Root cause in code: ClaudeAdapterV2.ts:279-280 \u2014 ClaudeAgentSdkQueryRunnerError.message hardcodes \"Claude Agent SDK query failed.\" and the underlying `cause` defect is never propagated into the projected failure. The failure IS user-visible (error item + run failed), but is undebuggable after the fact.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='7f1dfff1-4cbb-450b-8514-764d11c903e1' AND type='error';\"",
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Re-ran the repro: the error turn-item (event seq 25810) and run-attempt (seq 25811) for run ordinal 10 persist only {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null}, and the native log truly ends at 20:47:58.429Z with outgoing query.open/prompt.offer and no incoming SDK data, so no error detail exists anywhere in DB or provider log. Code confirms the mechanism: ClaudeAgentSdkQueryRunnerError.message is hardcoded at ClaudeAdapterV2.ts:279-280 and makeProviderFailure (ProviderFailure.ts:97-100) reads exactly that getter, dropping the Schema.Defect cause; the real cause only reaches an ephemeral Effect.logWarning. Other adapters (e.g. OpenCodeAdapterV2.ts:2202) propagate real detail, so this is an unintended gap, not design \u2014 finding stands at medium since the failure is user-visible but undebuggable after the fact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "401 authentication error result projected as successful run + plain assistant message",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native result at 2026-07-01T20:56:54.878Z has is_error=true with result 'Failed to authenticate. API Error: 401 Invalid authentication credentials'. Run run:thread:47763f5e-...:ordinal:1 is projected status='completed' (completed_at 20:56:54.916Z) and its provider_turn completed. The error text is user-visible only as a normal assistant_message (turn-item:provider:claudeAgent:native-item:94ed662f-814a-43d7-aad3-92e479b9dfe8, status=completed, type=assistant_message) \u2014 no error item, no failed status, so the run reads as a success.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE run_id='run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:1';\" vs grep -m1 '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 (is_error:true)",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced fully: native result at 20:56:54.878Z has subtype \"success\" with is_error:true and api_error_status:401, yet run ordinal:1 and its provider_turn are projected status=completed, and the error text survives only as a plain completed assistant_message item (94ed662f, itself the SDK's synthetic \"<synthetic>\"-model assistant message). Code confirms this is a gap, not intent: terminalStatusFromResult in ClaudeAdapterV2.ts only inspects message.subtype and the failure payload is attached only for non-\"success\" subtypes; is_error/api_error_status on result messages are never checked. The error text is user-visible via the SDK's synthetic message, but the run's structured status misreports failure as success and the 401 detail is not persisted, so medium severity stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Run 10 failure persisted with generic message only \u2014 no root cause anywhere",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run ordinal:10 failed in 0.5s (requested 22:48:37.674Z, completed 22:48:38.293Z). The only error record is the error turn-item terminal-failure...ordinal%25253A10 with failure {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}. The native log contains no error detail either \u2014 line 6324 (.log.1) shows the outgoing query.open at 22:48:38.086Z using create-style param sessionId:'b896a082-a480-416f-8ffd-c42845e71993' (after the session was closed at 22:41:50), then nothing incoming; the retry run 11 at 22:48:55.300Z used resume:'b896a082...' and succeeded. The actual SDK failure reason was never captured, and the failed open plausibly stems from reopening with sessionId instead of resume. Related: the query.close at 22:41:50 came ~31.8 min after run 9 completed (22:10:01) despite native wakeup activity through 22:38:55 \u2014 consistent with the known idle-session-reaper-vs-wakeup issue.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='error';\" and sed -n '6323,6327p' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Fully reproduced: run ordinal:10 failed in ~0.6s and the only persisted failure anywhere (turn-item event seq 29464) is the generic {class:transport_error, message:'Claude Agent SDK query failed.'}; the native log (.log.1 lines 6324-6325) shows query.open at 22:48:38.086Z with create-style sessionId after the 22:41:50 query.close, no incoming lines, then a successful resume-based retry at 22:48:55. The genericness is by construction: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:279-281) hardcodes its .message getter, defeating makeProviderFailure's cause.message extraction (ProviderFailure.ts), whose redaction/4096-char bounding shows real messages were intended to flow through. Even the fallback Effect.logWarning (server-child.log:457) collapsed the cause to '[Object]', so the root cause is unrecoverable from every persisted artifact \u2014 a real error-handling gap, though user-visibly surfaced and recovered by retry, so medium stands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Runs 11-13 projected as 'completed' although native result had is_error:true (API 529 Overloaded)",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native results in log.2: [2026-07-02T00:51:30.884Z], [00:55:19.085Z], [01:00:28.143Z] all 'subtype':'success','is_error':true,'num_turns':1 (preceded by 29 api_retry 'overloaded' events and one model_refusal_fallback at 00:51:30.857Z). Projections: runs ordinal 11/12/13 status 'completed', provider_turns 'completed'. The only user-visible signal is that the SDK emitted the error text as an assistant message (turn-item:provider:claudeAgent:native-item:9c0cead6-f253-44c8-8cc7-3c95b58a326e, run 13, text 'API Error: 529 Overloaded...'; run 11 item text 'API Error: Overloaded'). Run/attempt/turn statuses do not reflect the failure, so downstream logic treating these runs as successful is wrong.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT run_id,status FROM orchestration_v2_projection_runs WHERE run_id LIKE '%ea84f015%ordinal:1_' \" vs grep '\"is_error\":true' ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2",
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Evidence fully reproduces: log.2 has three decoded results with subtype 'success' but is_error:true (00:51:30.884Z 'API Error: Overloaded', 00:55:19.085Z api_error_status:529, 01:00:28.143Z), while runs ordinal 11/12/13 and their provider_turns project as 'completed' with matching completed_at timestamps, and the only trace is the error text projected as a completed assistant_message (item 9c0cead6-... on run 13). Code confirms the gap: terminalStatusFromResult in ClaudeAdapterV2.ts returns 'completed' for any subtype==='success' and attaches a failure payload only for non-success subtypes, even though the SDK's SDKResultSuccess type explicitly carries is_error and api_error_status \u2014 the signal is typed and available but ignored, so this is a real mapping bug, not intended behavior. Severity stays medium: the error is user-visible as assistant text, but structured run/attempt/turn statuses misreport success and the 529 detail is not queryable, which misleads any downstream logic."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Native ground truth for most of the session destroyed by rotation of the opener thread's log",
|
||||
"category": "lost-data",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Because codex traffic shares 71e29ba5's high-churn log (10 files x 10MB), the oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z. Everything earlier is deleted: c878541b runs 1-3 (01:54-15:58Z), all of de5f191a runs 1-3 (07:42-15:49Z), all of 68f7595b (05:53-05:56Z) and af66fc2c incl. its interrupted run (05:52-05:53Z). Only c878541b runs 4-6 (16:00-16:44Z) retain native logs. Consequence of the finding above; debuggability loss only \u2014 projections for the lost window exist and are internally consistent.",
|
||||
"repro": "for f in ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log*; do head -1 \"$f\" | cut -c2-25; done # earliest = 2026-07-01T16:00:59.024Z",
|
||||
"sessionKey": "codex-no-native-logs",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "low",
|
||||
"reasoning": "Evidence fully reproduces: oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z; DB run windows confirm c878541b runs 1-3, all of de5f191a/68f7595b/af66fc2c predate it; native item ids from c878541b run 1 (msg_024da2f2..., call_z8cGFhrA...) appear in zero log files while run 4's msg_0e493c0caf68... appears 82x in .log.10, and no dedicated logs exist for the codex threads because CodexAdapterV2's protocol logger is keyed to the shared session's opener thread. Downgraded to low: the loss is a by-design consequence of intentional bounded rotation (10x10MB in EventNdjsonLogger.ts), the durable pipeline record (events + projections) for the lost window is intact and consistent, and the actual defect (codex traffic sharing a high-churn foreign thread's rotation budget) is the parent finding this one merely derives from."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Terminal-failure error items carry only generic message ('Claude Agent SDK query failed.'), underlying cause not preserved",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 4 failed runs (37, 54 codex; 89, 119 claudeAgent) DO get a user-visible type='error' item (good surfacing), but payload is generic: run 119 item failure = {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}, title 'Provider error'. The native log at both claude failure sites (2026-07-02T04:47:07.200Z and 16:45:25.921Z) shows only outgoing query.open/prompt.offer with no captured error line, so neither projection nor provider log retains the actual failure reason \u2014 undebuggable after the fact.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure'), json_extract(payload_json,'$.title') FROM orchestration_v2_projection_turn_items WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND type='error'\"",
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"verdict": {
|
||||
"isReal": true,
|
||||
"adjustedSeverity": "medium",
|
||||
"reasoning": "Reproduced fully: claudeAgent failed runs 89/119 project only {class:'transport_error', message:'Claude Agent SDK query failed.', code:null} (event seq 43072), and the provider log at both failure sites (04:47:07.200Z log.2:790, 16:45:25.921Z log:3026) shows only outgoing query.open/prompt.offer with no error line. Source confirms the mechanism: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:280) hardcodes its message getter while the real error lives in its cause Defect, which makeProviderFailure (ProviderFailure.ts:90) never unwraps \u2014 defeating the redaction/bounding machinery built to carry real messages (codex failures on this same thread DO carry specific messages, proving intent). The adapter's Effect.logWarning with the full cause was not found in any retained server trace log, so the failure reason is genuinely lost; medium severity stands since errors are surfaced but undebuggable."
|
||||
}
|
||||
}
|
||||
],
|
||||
"refuted": [
|
||||
{
|
||||
"title": "Orchestrator ingestion gap 16:10-16:40 Jul 1 (codex era): 119 native command/fileChange items lost; assistant messages backfilled with flattened timestamps",
|
||||
"category": "lost-data",
|
||||
"severity": "high",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Zero orchestration_events for the stream between 2026-07-01T16:10:19 (run 50 completed) and 16:40:12 (run 51 requested), yet the native codex log shows substantive work in that window and around it: item/started fileChange items and commandExecutions incl. 'vp test .../OrchestratorReplayFixtures', 'vp check', 'git add apps/server/src/orchestration-v2/Adapters/Claude...' (call_0j3Wjk1K3an2l1CpCRgYBp8b 16:43:43) and 'git push origin t3code/codex-turn-mapping' (call_Hc9NQMOiQ9wo3by6RnzGbShQ 16:43:50), all with source 'unifiedExecStartup' on native thread 019f1b62-f532-79e2-9553-af817911965c. 119 of 450 native call_ ids have no projected turn_item (comm diff), all first seen 16:01-16:43 Jul 1. When run 51 started, 13 assistant messages (message:provider:codex:native-item:msg_*) were backfilled with IDENTICAL created_at 2026-07-01T16:40:14.821Z describing that missing work, but 0 turn_items have startedAt in 16:11-16:40. Text recovered, tool/file items and real timestamps lost. Mechanism (server down/restart vs codex turn-mapping bug) not fully determinable because logs older than 16:00:59Z were rotated away; loss itself is certain.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND occurred_at BETWEEN '2026-07-01T16:11' AND '2026-07-01T16:39'\" -> 0; SELECT count(*) FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at='2026-07-01T16:40:14.821Z' -> 13",
|
||||
"sessionKey": "71e29ba5-claude-mega",
|
||||
"verdict": {
|
||||
"isReal": false,
|
||||
"reasoning": "The \"lost\" work belongs to a different session: the codex provider session is shared, so this thread's log contains other threads' traffic. All gap-window log lines (1322 decoded events, 16:11-16:39) carry threadId 019f1b62-f532-..., which per orchestration_v2_projection_provider_threads is owned by thread c878541b-a832-..., not 71e29ba5 (whose codex nativeThreadRef is 019f1b50-4248-...). Exactly 119 call_ ids in the log belong to 019f1b62 and ALL 119 (including the cited call_0j3Wjk1K3an2l1CpCRgYBp8b and call_Hc9NQMOiQ9wo3by6RnzGbShQ) are projected on thread c878541b; all 62 call_ ids on this thread's own native id are projected on 71e29ba5 (comm diff = 0 both ways). The zero-event window is genuine idle time between run 50 (completed 16:10:19) and run 51 (requested 16:40:12), and the 13 messages at created_at 16:40:14.821Z are run 51's live-streamed assistant messages (e.g. msg_00c4d1e6... streamed at 16:48:38 on threadId 019f1b50) \u2014 every one of the 55 codex runs shows the same pattern of assistant messages sharing created_at = run start, so this is systematic projection behavior, not backfill of lost work."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "All thinking/reasoning blocks dropped for main thread (122 native thinking messages, 0 reasoning items)",
|
||||
"category": "lost-data",
|
||||
"severity": "medium",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains 122 distinct main-thread assistant messages with thinking content blocks plus 646 'thinking_tokens' system events, but the main thread has zero projected reasoning turn-items (the only 2 'reasoning' items in the session are subagent-progress placeholders on the child threads, e.g. turn-item:...task%3Aac08aa451ed54d3f6%3Aprogress). ClaudeAdapterV2.ts only extracts part.type==='text' blocks (line 730: content.flatMap((part) => (part.type === \"text\" ? [part.text] : []))). May be an intentional product choice for claudeAgent, but it means no reasoning is ever visible/persisted for this provider.",
|
||||
"repro": "cat log.1 log | jq 'select(.event.payload.type==\"assistant\" and .event.payload.parent_tool_use_id==null) | select([.event.payload.message.content[]?|select(.type==\"thinking\")]|length>0) | .event.payload.uuid' | sort -u | wc -l # 122, vs SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='reasoning'; -- 0",
|
||||
"sessionKey": "47763f5e-claude-fable",
|
||||
"verdict": {
|
||||
"isReal": false,
|
||||
"reasoning": "The counts reproduce (155 native thinking blocks, 0 projected reasoning items), but inspection of the actual block contents refutes the lost-data claim: every final thinking block in the native log is {\"thinking\":\"\",\"signature\":\"...\"} and all 593 thinking_delta stream events are {\"thinking\":\"\",\"estimated_tokens\":N} \u2014 the Claude Agent SDK redacted all thinking text at the source for claude-fable-5, so there was never any reasoning content to project. ClaudeAdapterV2.ts:730 extracting only text parts drops nothing user-visible here; projecting these blocks would produce 155 empty reasoning items. The 646 'thinking_tokens' system events are token telemetry, not content."
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Failed cursor runs 15/16/17 keep only a generic 'Provider turn failed.' with code:null \u2014 no diagnostic detail persisted",
|
||||
"category": "error-handling",
|
||||
"severity": "medium",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Error items exist and are user-visible (turn-item:provider:cursor:native-item:terminal-failure%3A...run-abf255cf / run-ceb09abc / run-f5fe7fcf, status failed, ordinals 15000098/16000002/17000002) but failure = {class:'provider_error', message:'Provider turn failed.', code:null, retryable:null}; run and run_attempt payloads contain no error field at all. Native run.completed results (log: 02:05:24.474Z, 02:16:37.138Z, 02:19:07.097Z) carry status:'error' with no message either \u2014 so cursor itself gave nothing \u2014 but available context (result.status, requestId d1cd7f44/55687657/6de8f367, durationMs 2434335/1223/657) was dropped. Run 15 did 40 min of work then errored; runs 16/17 ('continue') died in ~1s each with only 'Provider error' shown.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='ea84f015-e597-4f79-9557-d39b5a895fba' AND type='error'\"",
|
||||
"sessionKey": "ea84f015-cursor-handoff",
|
||||
"verdict": {
|
||||
"isReal": false,
|
||||
"reasoning": "The evidence reproduces (three failed cursor runs projected with the generic 'Provider turn failed.' failure), but the native log shows cursor's run.completed results carried status:'error' with NO error/message/code field at all, so there was no provider diagnostic to persist. The code path is intentional: CursorAdapterV2 forwards result.error as cause, and makeProviderFailure (ProviderFailure.ts) extracts message/code when supplied, falling back to the tested DEFAULT_PROVIDER_FAILURE_MESSAGE \u2014 including an explicit test asserting arbitrary cause objects are deliberately not serialized. The 'dropped context' claim largely fails: result.status is persisted as failed on item/run/provider_turn, and durationMs is recoverable from the persisted provider_turn startedAt/completedAt (01:24:50.203Z\u219202:05:24.475Z \u2248 2434335ms); only cursor's requestId is unpersisted, which the ProviderFailure contract intentionally omits and which remains in the provider log. This is an upstream cursor SDK limitation plus a possible enhancement (persist requestId), not a pipeline discrepancy.",
|
||||
"adjustedSeverity": "low"
|
||||
}
|
||||
}
|
||||
],
|
||||
"lowUnverified": [
|
||||
{
|
||||
"title": "Interrupt-result turn item references an interrupt-request parent that was never emitted",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "turn_item 'turn-item:run:run%3Athread%3Aea84f015-e597-4f79-9557-d39b5a895fba%3Aordinal%3A15:signal:interrupt-result' (event seq 34176, 2026-07-02T01:24:49.393Z) has parent_item_id '...:signal:interrupt-request' with no matching row/event. Contrast thread af66fc2c-73cd-4c30-bea5-66932ecdba29 where both request (seq 20000) and result (seq 20003) were emitted. Code: makeInterruptResultTurnItem in apps/server/src/orchestration-v2/RunExecutionService.ts (line ~874) unconditionally derives parentItemId from the request id without ensuring that item was emitted; the request emission lives on a separate path in Orchestrator.ts:4422.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, parent_item_id FROM orchestration_v2_projection_turn_items ti WHERE parent_item_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_turn_items p WHERE p.turn_item_id=ti.parent_item_id);\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "Synthesized terminal-failure error item references a provider_turn_id that was never projected",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "turn_item 'turn-item:provider:cursor:native-item:terminal-failure%3A...' on thread 721fc23c-2cf3-42bf-9d84-edd94359dca9 (updated 2026-06-29T21:48:40.703Z) carries providerTurnId 'provider-turn:provider:cursor:native-turn:failed%3Arun-attempt%3A...ordinal%253A2%3Aattempt%3A1' which has no row in orchestration_v2_projection_provider_turns. The run failed 4ms after the outgoing run.start ('what did you just say', log 2026-06-29T21:48:40.699Z) with no incoming response; the synthetic 'failed' turn id was minted for the failure item but the turn itself never projected.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items ti WHERE ti.provider_turn_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_provider_turns p WHERE p.provider_turn_id=ti.provider_turn_id);\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "provider_sessions stay status='ready' after provider-session.detached (projection ignores detach)",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Session provider-session:...claudeAgent:thread:47763f5e...:1c70abe8-4ecb-... got provider-session.detached event seq 31344 (2026-07-01T23:44:29.976Z, reason 'Thread archived.') and session ...ea84f015...:21ed85a2-... got detached seq 32566 (2026-07-02T01:03:00.273Z), yet both projection rows still show status='ready' with stale updated_at (22:48:37 / 22:12:31 \u2014 predating even later provider-session.updated events like seq 31274 at 23:42:43). The 16 'stopped' sessions were transitioned via updated events; detach alone leaves rows 'ready' indefinitely on archived threads.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT s.provider_session_id, s.status, s.updated_at FROM orchestration_v2_projection_provider_sessions s WHERE s.status='ready' AND EXISTS (SELECT 1 FROM orchestration_events e WHERE e.event_type='provider-session.detached' AND e.payload_json LIKE '%'||s.provider_session_id||'%');\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "13 backgrounded local_bash tasks projected as subagents with empty prompts and synthetic child threads",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Thread 7f1dfff1-4cbb-450b-8514-764d11c903e1 run 2 (2026-07-01T15:51): tasks bw28jiyac, bzmkw8629, bnkw62tp7, etc. are task_type 'local_bash' in the native log (task_started has only a 'description' like 'vp run --filter @t3tools/web typecheck...', no prompt), yet each got a subagent row (prompt length 0), a child thread, and a user_message prompt item with text ''. Newer local_agent tasks (a-prefixed 16-hex ids) capture full prompts (1.9k-4.3k chars). Predates the backgrounded-Bash redesign on t3code/codex-turn-mapping where local_bash stays a running Bash item completed cross-run; these are stale artifacts of the old mapping, not current behavior.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE type='user_message' AND coalesce(json_extract(payload_json,'$.text'),'')='';\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "Cursor stream stall: abandoned partial-tool-call finalized as 'completed'; provider retry duplicated assistant text",
|
||||
"category": "duplicate",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Thread ea84f015 run 15: partial-tool-call toolu_01HgLigck78NC9MSVyjitDXe (edit) at log 2026-07-02T01:54:20.622Z never received tool-call-started/completed (stream stalled 6.5 min, cursor retried at 02:00:47 with new callId toolu_01NkWmCzHTn5ofjtYi4NkhsJ); the abandoned call's item 'turn-item:provider:cursor:native-item:toolu_01HgLigck78NC9MSVyjitDXe' (type file_change) was finalized status='completed' at run end (02:05:24.475Z) though the edit never executed. The retry also re-emitted identical assistant text ('Now the `WorkGroupSection` filter and the `SimpleWorkEntryRow` indicator.') producing items ...abf255cf...%3A6 (ordinal 15000077) and %3A7 (15000079) with duplicate visible text \u2014 faithful to two native text-delta emissions (log 01:54:19.813Z and 02:00:47.715Z), so provider-side, but rendered twice to the user.",
|
||||
"repro": "grep -a 'SimpleWorkEntryRow\\` indicator' ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log | cut -c1-30",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "provider_turn status has no 'waiting' literal during ScheduleWakeup sleep loops",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": true,
|
||||
"evidence": "Known issue per assignment; currently only 1 provider_turn 'running' (thread 71e29ba5, started 2026-07-02T17:03:04.470Z \u2014 genuinely live at audit time 17:07Z), so no stale instance observed in this pass, but the schema/status distribution confirms no 'waiting' state exists (statuses seen: cancelled/completed/failed/interrupted/running).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, count(*) FROM orchestration_v2_projection_provider_turns GROUP BY status;\"",
|
||||
"sessionKey": "GLOBAL"
|
||||
},
|
||||
{
|
||||
"title": "Codex reasoning items never ingested (no content lost in this session: all summaries empty)",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains 5 reasoning item/completed events (e.g. rs_0cfa4cea83165175016a40a8e17de08199a84ec646c88a40cd run 2, rs_0cfa4cea...8c48/9052/9329 run 4), all with summary: []. SQL: 0 orchestration_events on stream a5a643b2-... with payload LIKE '%native-item:rs_%', and 0 turn_items of reasoning type with a codex provider_thread anywhere in the DB (172 reasoning items exist for other providers). CodexAdapterV2.ts has no reasoning item mapping (grep hits only 'reasoningEffort' config). With empty summaries nothing user-visible was lost here, and dropping empty reasoning may be intentional, but non-empty reasoning summaries would be silently dropped.",
|
||||
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log | jq -c 'select(.event.stage==\"decoded\") | .event.payload | select(.method==\"item/completed\" and .params.item.type==\"reasoning\")' | wc -l # 5, vs sqlite count 0",
|
||||
"sessionKey": "a5a643b2-codex-heya"
|
||||
},
|
||||
{
|
||||
"title": "Codex reasoning items are silently dropped by CodexAdapterV2 (no handler for item type \"reasoning\")",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log emits item/started + item/completed for reasoning item rs_056ea93bc8adc0f3016a42c0594d788194ad4afb537a0a0b16 at 2026-06-29T18:58:33.314Z/33.340Z (turn 019f14bf-4440-7bb0-9655-7194b384e690), but zero rows in orchestration_events reference it and no turn_item exists. Code confirms: CodexAdapterV2.ts item/started (line 2802) and item/completed (line 2875) handlers cover userMessage, subAgentActivity, commandExecution, mcpToolCall/dynamicToolCall, fileChange, webSearch, plan, collabAgentToolCall, agentMessage \u2014 no \"reasoning\" branch and no item/reasoning delta handler, despite capabilities declaring streamsReasoning: true (line 139). In THIS session the item had empty summary/content so no user-visible text was lost, hence severity low \u2014 but any non-empty reasoning summary would vanish.",
|
||||
"repro": "grep 'rs_056ea93bc8adc0f3' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log ; sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%rs_056ea93bc8adc0f3%'\" -- returns 0",
|
||||
"sessionKey": "a61e9269-codex"
|
||||
},
|
||||
{
|
||||
"title": "thread/tokenUsage/updated and account/rateLimits/updated notifications never ingested; runs have no usage data",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains 5 thread/tokenUsage/updated and 5 account/rateLimits/updated decoded notifications; CodexAdapterV2.ts registers no handler for either (only item/agentMessage/delta, item/plan/delta, turn/plan/updated, turn/started, item/started, item/completed, turn/completed at lines 2693-3395). Runs projection payload has usage:null for both run:thread:a61e9269-0180-4f4c-988a-aca00b240469:ordinal:1 and :2, and no orchestration_events row carries token usage. May be intentional scope, but per-turn token accounting from the provider is discarded.",
|
||||
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log | jq -r 'select(.event.stage==\"decoded\") | .event.payload.method' | grep -c tokenUsage",
|
||||
"sessionKey": "a61e9269-codex"
|
||||
},
|
||||
{
|
||||
"title": "Child task threads projecting only 2 items is intended, not data loss",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Each child stream (e.g. ...composer_call_kFjs8) has exactly 2 distinct turn-item ids across its 2711 events: ...%3Aprompt (user_message, 1 event) and ...%3Aresult (assistant_message, 1352 events growing text 4->6274 chars). Grok's ACP Task envelope only exposes rawInput.prompt plus streamed output text (apps/server/src/provider/acp/XAiAcpExtension.ts extractXAiAcpSubagentUpdate / xAiTaskOutputText), and the child's intermediate narration is contained in the streamed result text ('I'll read the connection files...'). Parent subagent items' result lengths (3721/6274/2647) exactly equal child assistant_message text lengths \u2014 nothing truncated.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.id'), COUNT(*), MAX(length(json_extract(payload_json,'$.text'))) FROM orchestration_events WHERE stream_id LIKE '%composer_call_kFjs8' AND event_type='turn-item.updated' GROUP BY 1;\"",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Every successful grok turn logs session/prompt as failed with errorTag Interrupt",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log events ec0b4762-8c1d-41c9-b4b3-2687da09d40b (2026-06-29T21:46:13.448Z) and 5a4a5b58-40ad-4f71-b2de-6e703e0c9173 (21:47:37.827Z): payload {method:'session/prompt',status:'failed',errorTag:'Interrupt'} \u2014 yet both runs completed successfully (run ordinal 1 completedAt 21:46:13.476Z, ordinal 2 completedAt 21:47:38.686Z). Cause: XAiAcpExtension races the direct prompt request against the private _x.ai/session/prompt_complete fallback; the losing fiber is interrupted and logged as a failed request. Correctly NOT surfaced as a user-visible error (nothing to surface), but the 'failed' log entries are misleading noise for future debugging.",
|
||||
"repro": "grep '\"status\":\"failed\"' ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Grok native log redacts all payload content, limiting ground-truth audits",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 3694 protocol lines in ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log carry only shape summaries, e.g. payload {valueType:'string',byteLength:165} or {valueType:'array',itemCount:1} \u2014 no message text, tool names, or ids. Content-level loss/truncation verification against the provider is impossible from this log; verification here relied on internal consistency (event max text length == projection text length). If other providers' logs contain full JSON, grok's redaction is an inconsistency worth knowing about.",
|
||||
"repro": "grep -c 'byteLength' ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Child task thread items carry null run_id/provider_thread_id/provider_turn_id",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 6 child items have runId=null, providerThreadId=null, providerTurnId=null (e.g. turn-item ...composer_call_Olv1X%3Aprompt payload: runId:null, nodeId:'node:...%3Achild-root', creationSource:'provider'); child threads have zero run.created / provider-turn events. node_id resolves (child-root nodes exist) and the subagents projection links parent node -> child_thread_id, so navigation works via subagents rather than runs. Appears intentional for provider-native task children (no orchestrator run exists), but any consumer that groups items by run_id will see these as orphans.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, run_id, provider_turn_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:grok:native-thread:019f1558%';\"",
|
||||
"sessionKey": "20296b49-grok-tasks"
|
||||
},
|
||||
{
|
||||
"title": "run_attempts.provider_turn_id is never populated (null for all 207 attempts DB-wide) \u2014 back-link from attempt to provider turn missing",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "This session: run-attempt:run:run%3Athread%3A721fc23c...%3Aordinal%3A1:attempt:1 has providerTurnId:null although provider-turn:provider:cursor:native-turn:run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 references that exact runAttemptId (forward link intact, nativeTurnRef strong). Global check: SELECT provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1 shows every row (completed 188, failed 12, cancelled 4, interrupted 1, running 1, superseded 1) has NULL \u2014 the column/payload field exists but nothing ever writes it. Forward resolution via provider_turns.run_attempt_id works, so impact is limited to reverse-lookup ergonomics; may be intentional but the schema advertises the field.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1,2\"",
|
||||
"sessionKey": "721fc23c-cursor"
|
||||
},
|
||||
{
|
||||
"title": "Run orphaned by server restart is cancelled with no user-visible or persisted reason; user's message got no response",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log ends at run.started 2026-06-29T21:49:09.097Z (runId run-f062e5d9-534a-48a8-8214-48fea97bc268) with zero assistant output. Events seq 6341-6346 (command:runtime-reconcile:startup:48663fb7-...:2026-06-29T21:49:10.775Z) set run:thread:48663fb7-...:ordinal:1, its attempt, and provider-turn:provider:cursor:native-turn:run-f062e5d9-... to status 'cancelled' with no reason field in any payload, indistinguishable from a user cancel. No error/system turn_item was emitted, so the timeline shows only the user 'hello' and 'Workspace ready' with nothing explaining the missing reply. Source: ProviderRuntimeRecoveryService.ts:107 builds detail 'Cancelled because the server restarted before the provider work completed.' but attaches it only to runtime-request payloads and outbox effect cancellations (lines 291/316), never to run/attempt/turn/item rows \u2014 intentional code path, but a debuggability/UX gap.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, payload_json FROM orchestration_events WHERE stream_id='48663fb7-fbd6-4be2-ad14-d8163282c069' AND command_id LIKE 'command:runtime-reconcile:%'\" \u2014 note status 'cancelled' payloads contain no reason; and grep -c NTIVE ~/.t3/userdata-v2/logs/provider/48663fb7-fbd6-4be2-ad14-d8163282c069.log shows only 4 lines with no assistant output.",
|
||||
"sessionKey": "48663fb7-cursor"
|
||||
},
|
||||
{
|
||||
"title": "file_search items never carry results (read/grep/glob outputs dropped) despite contract supporting them",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 117 file_search items across the 5 opencode child threads have results=NULL (contract OrchestrationV2FileSearchResult array at orchestrationV2.ts:843 is never populated by OpenCodeAdapterV2 \u2014 its file_search branch emits only 'pattern'). Example: prt_f15688536002X4CTVKyjMIxGfL (ses_0ea978228, ordinal 3) has only pattern '/Users/julius/Development/Work/codething-mvp'. Tool outputs (file contents read, matches found) exist in opencode's part.state.output but are discarded for this item type. Likely intentional UI minimalism, but it is provider-emitted content with no projection.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*), SUM(json_extract(payload_json,'$.results') IS NOT NULL) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:opencode:native-thread:ses_%' AND type='file_search';\" -- returns 117|0",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Placeholder 'pending' provider_thread row persists alongside the real one; orchestrator-synthesized items split across the two",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Main thread has TWO provider_thread rows: provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A3029dc85...%3Aordinal%3A1 (status idle, first/last run ordinals 1-7) and the real provider-thread:provider:opencode:native-thread:ses_0ea983868ffens4ayJQLKgPE6J (idle, 1-7). 20 items (7 user_message, 7 checkpoint, 3 thread_created, 2 delegated subagent, 1 command_execution) still reference the pending placeholder while all native items reference ses_0ea983868 \u2014 e.g. thread_created item turn-item:created-thread:...126456a2...%3A0 has providerThreadId '...pending%3Arun%3A...ordinal%3A1' but providerTurnId pointing at the real session ses_0ea983868. Lineage is queryable but split; the placeholder was never collapsed after the native session id was learned.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id, status, first_run_ordinal, last_run_ordinal FROM orchestration_v2_projection_provider_threads WHERE thread_id='3029dc85-93b7-43c5-8993-1beff41b1c98';\"",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Single occurred_at inversion on main stream (checkpoint capture vs concurrent subagent-result handoff)",
|
||||
"category": "ordering",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Stream 3029dc85...: stream_version 1868 (sequence 10004, checkpoint.captured, occurred_at 2026-06-29T22:09:54.344Z, checkpoint root:name:5 for run 5) was appended AFTER stream_versions 1863-1867 (sequences 9881-9885, delegated subagent d43de13f completion + context-handoff/transfer, occurred_at 22:09:54.779Z) \u2014 occurred_at goes backwards by 435ms. Benign concurrency between run-5 completion checkpointing and the delegated claudeAgent subagent result handoff landing; projection ordinals unaffected (0 ordinal inversions vs first-seen event order across all 6 threads).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT stream_version, sequence, event_type, occurred_at FROM (SELECT stream_version, sequence, event_type, occurred_at, LAG(occurred_at) OVER (ORDER BY stream_version) prev FROM orchestration_events WHERE stream_id='3029dc85-93b7-43c5-8993-1beff41b1c98') WHERE occurred_at < prev;\"",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Native provider log payloads are fully redacted (valueType/fieldCount only), preventing content-level loss auditing",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Every one of the 17,198 log lines in 3029dc85-93b7-43c5-8993-1beff41b1c98.log(.1) has kind='protocol' with inner payload reduced to {valueType:'object', fieldCount:N} \u2014 e.g. message.part.updated lines carry no part id, text, or error. Only method-level counts are auditable (15,542 message.part.delta, 723 message.part.updated, 204 message.updated, 7 session.promptAsync, 5 session.created, 12 session.idle). Method counts DO reconcile with projections (7 promptAsync = 7 runs; 5 session.created = 5 child threads; 12 session.idle = 7 main turns + 5 child turns), but text truncation and the actual error string of the failed file_search cannot be verified against the wire. If these logs are meant to be 'ground truth', the opencode SSE logger is not recording decoded payloads.",
|
||||
"repro": "grep -h '\"message.part.updated\"' ~/.t3/userdata-v2/logs/provider/3029dc85-93b7-43c5-8993-1beff41b1c98.log.1 | head -1",
|
||||
"sessionKey": "3029dc85-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Split provider-thread identity: run/attempt/provider_turn reference the pending-keyed provider-thread row while turn items and threads.active_provider_thread_id reference the ses_-keyed row",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Two rows in orchestration_v2_projection_provider_threads for the same native session: 'provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A9f8d616d-...%3Aordinal%3A1' and 'provider-thread:provider:opencode:native-thread:ses_0ea7ea5deffe0eNd8RbfyTfgAw' (both idle, same provider_session_id, and the pending row's payload has nativeThreadRef.nativeId=ses_0ea7ea5deffe0eNd8RbfyTfgAw strength strong). projection_runs.provider_thread_id, run_attempts.provider_thread_id and provider_turns.provider_thread_id all point at the pending-keyed row, while the two provider-part turn_items (prt_f158168eb001r0Ubqqry5Z31Q1, prt_f158169d0002CgOsT8eNRkPGI3) and threads.active_provider_thread_id point at the ses_-keyed row. Notably provider_turns row provider-turn:...ses_0ea7ea5deffe0eNd8RbfyTfgAw%3Aattempt... encodes ses_ in its own id but its provider_thread_id column is the pending row. Pending id minted in Orchestrator.ts (`nativeThreadId: \\`pending:${runId}\\``, lines 2384/2772); the pending row is resolved via nativeThreadRef rather than rebinding downstream rows, so joins on provider_thread_id split the turn across two ids.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id FROM orchestration_v2_projection_provider_turns WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3'; SELECT DISTINCT provider_thread_id FROM orchestration_v2_projection_turn_items WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3';\"",
|
||||
"sessionKey": "9f8d616d-opencode"
|
||||
},
|
||||
{
|
||||
"title": "Real provider-thread row stayed status 'active' for ~20h after the provider session stopped",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "provider-session.updated seq 13792 marks session stopped at 2026-06-29T23:00:38.028Z (idle reaper ~30min after last activity 22:30:30; last native log line heartbeat 2026-06-29T23:00:27.024Z). The pending-keyed provider-thread went idle at turn completion (seq 13783, 22:30:30.877Z), but the ses_0ea7ea5deffe0eNd8RbfyTfgAw provider-thread's last status update before shutdown was 'active' (seq 13779, 22:30:30.876Z) and it was only flipped to idle by seq 13797 at 2026-06-30T18:59:15.308Z, ~20h later (presumably on next app start). During that window the projection showed an active provider-thread bound to a stopped session. Eventually reconciled; final state is consistent.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.id'), json_extract(payload_json,'$.status') FROM orchestration_events WHERE stream_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3' AND event_type IN ('provider-thread.updated','provider-session.updated') ORDER BY sequence\"",
|
||||
"sessionKey": "9f8d616d-opencode"
|
||||
},
|
||||
{
|
||||
"title": "OpenCode native log payloads are redacted to shape summaries, preventing content-level ground-truth verification",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Every one of the 273 lines in 9f8d616d-86ee-4560-bd52-2387d6adb1c3.log is kind 'protocol' (opencode-sdk.sse) with payload reduced to e.g. {\"payload\":{\"valueType\":\"object\",\"fieldCount\":3}} \u2014 no message text, part ids, or tool args (contrast with claude logs which carry full decoded JSON). Only method names/counts are auditable: 31 message.part.delta, 7 message.part.updated, 6 message.updated, 1 session.idle, 0 session.error. Projected content was spot-checked instead and looks sensible and un-truncated (user 'hey'; reasoning 'The user is just saying \"hey\" - a casual greeting...'; assistant 'Hey! What can I help you with?').",
|
||||
"repro": "sed -E 's/^\\[[^]]+\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/9f8d616d-86ee-4560-bd52-2387d6adb1c3.log | jq -r '[.event.payload.direction,.event.payload.method]|@tsv' | sort | uniq -c",
|
||||
"sessionKey": "9f8d616d-opencode"
|
||||
},
|
||||
{
|
||||
"title": "run_attempt.provider_turn_id never populated (null on all 207 attempts DB-wide)",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "run-attempt row run-attempt:...ordinal%3A1:attempt:1 has providerTurnId:null in payload_json and empty provider_turn_id column, while the provider_turn row correctly back-references runAttemptId. DB-wide: SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts \u2192 207|0. Forward lineage attempt\u2192turn is only recoverable by scanning provider_turns; may be intentional (reverse-only linkage) but the column exists and is never filled.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts;\"",
|
||||
"sessionKey": "1156181e-delegated-task"
|
||||
},
|
||||
{
|
||||
"title": "Provider session stayed 'running' ~25h after turn ended; only reconciled to 'stopped' at server shutdown",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": true,
|
||||
"evidence": "Turn completed 2026-06-28T05:22:33.360Z (last native log line); no further session events until sequence 168 provider-session.updated at 2026-06-29T06:33:36.481Z via command:runtime-reconcile:shutdown, which set status=stopped. No provider-session.detached was ever emitted for this thread. Related to the known idle-session-reaper/session-lifecycle area; state is correct now, so no data impact, but the projection reported a live session for a day for a one-shot delegated task.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, occurred_at FROM orchestration_events WHERE stream_id LIKE '%1156181e%' AND event_type LIKE 'provider-session%' ORDER BY sequence;\"",
|
||||
"sessionKey": "1156181e-delegated-task"
|
||||
},
|
||||
{
|
||||
"title": "claudeAgent provider sessions never idle-reaped; stayed 'ready' ~21 hours until simultaneous shutdown sweep",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "codex session stopped 2026-06-29T22:39:55 (seq 13789, 30 min after its 22:09:55 failure) and grok stopped 22:41:44 (seq 13790, 30 min after 22:11:44 completion) \u2014 idle reaper working. But all 3 claudeAgent sessions (last activity 22:08:48 / 22:09:50 / 22:13:07 on 6/29) only transitioned ready->stopped at 2026-06-30T18:59:15.286/.289/.291 (seq 13793-13795), simultaneously, ~21h later \u2014 a shutdown sweep, not the 30-min reaper. Native logs show no claude activity after 22:13, so either processes lingered or projections misreported 'ready' for a day. Inverse of the known 'reaper kills long sleeps' issue: reaper never fired for claudeAgent.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.status') FROM orchestration_events WHERE event_type LIKE 'provider-session%' AND stream_id LIKE '%6d618dc4%' ORDER BY sequence;\"",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Codex model-rejection error fully preserved and user-visible (works as intended)",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log 22:09:55.424 method 'error' / turn/completed status failed with message 'The gpt-5.3-codex model is not supported when using Codex with a ChatGPT account' (400 invalid_request_error). Projection: turn_item turn-item:provider:codex:native-item:terminal-failure%3A...019f156e-851a... type=error status=failed carries the verbatim JSON error in failure.message; run/run_attempt/provider_turn all 'failed'. No swallowing \u2014 this is a positive verification, listed for completeness.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE turn_item_id LIKE '%terminal-failure%019f156e-851a%';\"",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Grok session/prompt request ends with errorTag 'Interrupt' at the instant the turn completes",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "low",
|
||||
"knownIssue": false,
|
||||
"evidence": "Log 2026-06-29T22:11:44.909Z: {method:'session/prompt',status:'failed',errorTag:'Interrupt'} while provider_turn 019f156e-797f...:turn:1 completedAt 22:11:44.910 status=completed and the 6663-char assistant report is fully projected (item ordinal 1000074). Likely adapter-initiated interrupt cleanup after observing turn completion (grok capabilities: supportsSteeringByInterruptRestart=true); no data lost, but a native 'failed' prompt request maps to a 'completed' turn, which could confuse future debugging.",
|
||||
"repro": "grep '\"method\":\"session/prompt\",\"status\":\"failed\"' ~/.t3/userdata-v2/logs/provider/thread-mcp-6d618dc4-25fd-453b-9193-fd22a6739d1f-126456a2-f1ff-4098-a0a0-fde04bb1.log",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Grok file_search/read items persist only pattern + fileName echo, no tool output; grok native log fully redacted",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "low",
|
||||
"knownIssue": false,
|
||||
"evidence": "49 file_search items on thread :1 store e.g. pattern='pnpm-workspace.yaml', results=[{'fileName':'pnpm-workspace.yaml'}] (item turn-item:provider:grok:native-item:...call-e4489e09-...-1, ordinal 1000004) \u2014 the file content the tool returned is not kept, unlike claudeAgent command items which keep full stdout envelopes. Additionally the grok log redacts all decoded payloads to shape summaries ({'valueType':'array','itemCount':1}), so native-vs-projection content verification is impossible for grok; command_execution and reasoning items do carry real content, so this may be an intentional thin mapping for read-style tools.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.pattern'), json_extract(payload_json,'$.results') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:1' AND type='file_search' LIMIT 5;\"",
|
||||
"sessionKey": "6d618dc4-mcp-group"
|
||||
},
|
||||
{
|
||||
"title": "Both session/prompt requests logged as failed with errorTag=Interrupt despite runs completing",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log request events: session/prompt started 01:51:45.517 -> failed errorTag=Interrupt at 01:52:13.249; session/prompt started 01:53:00.071 -> failed errorTag=Interrupt at 01:53:37.665. These timestamps exactly equal provider_turn completed_at values (turn 1: 01:52:13.249, turn 2: 01:53:37.665), and both runs/turns/items project as completed with full assistant content, so this appears to be intentional adapter teardown (interrupting the pending ACP prompt fiber once the turn result is reached; grok sets interruptPromptOnCancel:false in GrokAdapterV2.ts line 90/641). No content was lost and no spurious failure surfaced, but the log-level 'failed' status for successful turns will mislead debugging.",
|
||||
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/5dcea72d-15e1-4ded-922b-0b00c587de6c.log | jq -c 'select(.event.kind==\"request\" and .event.payload.method==\"session/prompt\")'",
|
||||
"sessionKey": "5dcea72d-grok-subagent"
|
||||
},
|
||||
{
|
||||
"title": "run_attempts.provider_turn_id never populated (reverse link only)",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Both attempts for this session (run-attempt:run:run%3Athread%3A5dcea72d...ordinal%3A1:attempt:1 and ...ordinal%3A2:attempt:1) have provider_turn_id NULL in both the column and payload_json; DB-wide, 0 of all rows in orchestration_v2_projection_run_attempts have a non-NULL provider_turn_id. Lineage is still resolvable via orchestration_v2_projection_provider_turns.run_attempt_id (both turns correctly reference their attempts), so this may be an intentionally unused column, but the forward link is dead.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_v2_projection_run_attempts WHERE provider_turn_id IS NOT NULL;\"",
|
||||
"sessionKey": "5dcea72d-grok-subagent"
|
||||
},
|
||||
{
|
||||
"title": "Backgrounded-bash child threads have empty-text prompt user_message items",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 13 backgrounded-bash child threads project a user_message item task%3A<id>%3Aprompt with text:\"\" (e.g. turn-item:provider:claudeAgent:native-item:task%3Abw28jiyac%3Aprompt, startedAt 2026-07-01T15:51:26.160Z), even though the native task_started event carried description \"vp run --filter @t3tools/web typecheck 2>&1 | tail...\". The command is still user-visible via the main-thread subagent item title, so impact is cosmetic (empty bubble if the child thread is opened).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%7f1dfff1%' AND type='user_message' AND json_extract(payload_json,'$.text')='';\"",
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Codex run 1 (169 items) has no surviving native log to verify against",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run ordinal 1 (codex, 2026-07-01T01:45:03Z\u201302:01:10Z, 169 items incl. 10 failed command_executions) predates the oldest surviving log rotation: 7f1dfff1-...log.1 first line is 2026-07-01T15:48:00.224Z (run 2). The codex portion of the log was rotated away, so item-level loss/ordering for run 1 could not be ground-truthed; its events/projections are internally consistent (contiguous ordinals 1000001-1000169, all terminal).",
|
||||
"repro": "head -1 ~/.t3/userdata-v2/logs/provider/7f1dfff1-4cbb-450b-8514-764d11c903e1.log.1",
|
||||
"sessionKey": "7f1dfff1-claude-scheduled-tasks"
|
||||
},
|
||||
{
|
||||
"title": "Provider session projection stuck at status 'ready' after detach/archive",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "provider-session.detached event at 2026-07-01T23:44:29.976Z (reason 'Thread archived.') for provider-session:...:1c70abe8-4ecb-43f8-8ee6-9ce19beddcfe, but the orchestration_v2_projection_provider_sessions row still shows status='ready' with updated_at=2026-07-01T22:48:37.724Z and thread_id still bound. The event stream also shows the session flip stopped\u2192ready correctly at 22:41:50/22:48:37, so the projection simply never reflects the final detached/terminated state.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, updated_at FROM orchestration_v2_projection_provider_sessions WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514';\"",
|
||||
"sessionKey": "47763f5e-claude-fable"
|
||||
},
|
||||
{
|
||||
"title": "Detached claudeAgent provider session left in status 'ready' forever after handoff",
|
||||
"category": "stuck-state",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Event seq 32566 provider-session.detached at 2026-07-02T01:03:00.273Z (reason 'Provider or model selection changed.') for provider-session:provider-instance:claudeAgent:thread:ea84f015-...:21ed85a2-2ed1-4bd8-94be-1e5affe1aa72, but the orchestration_v2_projection_provider_sessions row still shows status='ready' \u2014 no stopped update was ever emitted. The replacement cursor session was correctly moved to 'stopped' at 02:49:07 (seq 38639).",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT provider_session_id,status FROM orchestration_v2_projection_provider_sessions WHERE provider_session_id LIKE '%ea84f015%'\"",
|
||||
"sessionKey": "ea84f015-cursor-handoff"
|
||||
},
|
||||
{
|
||||
"title": "Subagent child-thread items have null run_id / provider_thread_id / provider_turn_id",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "All 34 items of child thread ...a4bd1db1834cb086a and 52 items of ...ab96794f302d5fd03 have runId:null, providerThreadId:null, providerTurnId:null (e.g. turn-item:provider:claudeAgent:native-item:toolu_01L5SAT2nkGMce3gWf3qFFqJ). Lineage back to the parent exists only via orchestration_v2_projection_subagents (child_thread_id set, run_id = parent runs ordinal 2 and 5, both completed) and the two parent subagent turn items (task%3Aa4bd1db1834cb086a%3Asubagent / task%3Aab96794f302d5fd03%3Asubagent). Likely by design (child threads have no runs of their own), but items cannot be joined to any run/turn directly.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:claudeAgent%ea84f015%' AND run_id IS NULL\"",
|
||||
"sessionKey": "ea84f015-cursor-handoff"
|
||||
},
|
||||
{
|
||||
"title": "error_during_execution result during run 5 coincides with steering message \u2014 absorbed without any projected trace",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "log.3 line 677 [2026-07-01T23:13:24.083Z] result subtype error_during_execution, is_error:true, duration_api_ms 2473149, session 44cbb4c7. A user steering message was ingested 50ms earlier (seq 30447 message.updated 23:13:24.031Z, message 513621d3-5a03-46e1-8fd7-cc4de4b417f1, run 5), so this looks like the intentional interrupt-for-steering path; run 5 continued and completed at 23:30:07 with items after 23:13. No event records the aborted query, which is acceptable if intentional but leaves no audit trail of the abort.",
|
||||
"repro": "grep -n error_during_execution ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log.3",
|
||||
"sessionKey": "ea84f015-cursor-handoff"
|
||||
},
|
||||
{
|
||||
"title": "5 tool calls that never returned natively were auto-marked 'completed' (with no results) at turn end",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log has 123 distinct tool-call-started but only 118 tool-call-completed; the 5 without completion (tool_e1f3ce39... glob, tool_fd1ba594..., tool_e2f6262c..., tool_840aeaa9... grep, tool_671d1b53... read) are all projected as status 'completed' with completedAt forced to the turn-end timestamp 2026-07-02T02:25:57.991Z and no results payload (e.g. turn-item:provider:cursor:native-item:tool_e1f3ce39-4604-4ced-8039-bbd5e75946b ends with pattern:'**/*' and no results field). This is the intentional finalizeTurn flush (CursorAdapterV2.ts:1886-1889 emitToolArtifacts({completed:true})), but 'completed' misrepresents tools whose results never arrived; something like 'interrupted' or an explicit no-result marker would be more truthful. Minor: cursor itself abandoned these calls, so no user-visible content was lost.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.completedAt') FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_e1f3ce39-4604-4ced-8039-bbd5e75946b';\"",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns"
|
||||
},
|
||||
{
|
||||
"title": "Run 2 was a 7.3-minute silent hang before failing \u2014 nothing projected during the window (faithful to provider, but no progress/heartbeat signal exists)",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log: run.started for run-f4d64e64 at 02:28:07.973Z, next event is run.completed status 'error' at 02:35:28.424Z \u2014 zero interaction.updates in between. Ingested events for the stream in that window: 0 (SELECT COUNT(*) ... occurred_at BETWEEN '02:28:09' AND '02:35:28' returns 0). The pipeline mirrors the provider exactly (nothing lost), but the projection offers no signal distinguishing 'model working' from 'SDK dead due to auth error' during those 440s; the user just saw a running turn that eventually failed generically.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE stream_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND occurred_at > '2026-07-02T02:28:09' AND occurred_at < '2026-07-02T02:35:28';\"",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns"
|
||||
},
|
||||
{
|
||||
"title": "Native 'read' tool calls are projected as type 'file_search'",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "18 native 'read' tool calls (e.g. tool_671d1b53-bb49-46ef-94de-8f682391c93 reading a file path) are projected as type 'file_search' with the file path as 'pattern'. Intentional per CursorAdapterV2.ts:1203-1219 (glob/grep/read/ls/readLints/semSearch all map to file_search), so the content is preserved, but the item type flattens semantically distinct operations (file reads rendered as searches). Cosmetic fidelity note only.",
|
||||
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT type FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_671d1b53-bb49-46ef-94de-8f682391c93';\"",
|
||||
"sessionKey": "c9e72a05-cursor-failing-turns"
|
||||
},
|
||||
{
|
||||
"title": "Token usage from turn-ended/run.completed is dropped by the ingestion pipeline",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log line 663 (2026-07-02T07:08:07.565Z) turn-ended carries usage {inputTokens:596379, outputTokens:6430, cacheReadTokens:522080}; line 664 run.completed repeats it with totalTokens:1124889. No event for stream_id=8ee00dcc-fa04-4fe7-9920-cd3432d45415 contains 'usage' or 'Tokens' (query returned 0 rows), and neither the run nor provider_turn projection payloads have a usage field. grep for 'usage' in apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts, ProviderEventIngestor.ts and ProviderAdapter.ts returns nothing \u2014 the v2 contract simply doesn't model usage, so this looks like a pipeline-wide design gap rather than a session bug, but users lose per-turn token/cost data.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND payload_json LIKE '%Tokens%';\" (returns 0) vs grep -c 'inputTokens' ~/.t3/userdata-v2/logs/provider/8ee00dcc-fa04-4fe7-9920-cd3432d45415.log (returns 2)",
|
||||
"sessionKey": "8ee00dcc-cursor-spacing"
|
||||
},
|
||||
{
|
||||
"title": "run_attempt.provider_turn_id never backfilled (forward link missing; reverse link intact)",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "orchestration_v2_projection_run_attempts row run-attempt:run:run%3Athread%3A8ee00dcc-fa04-4fe7-9920-cd3432d45415%3Aordinal%3A1:attempt:1 has provider_turn_id='' and payload providerTurnId:null even after completion, while orchestration_v2_projection_provider_turns row provider-turn:provider:cursor:native-turn:run-ee800ef2-cd0e-45bd-9481-65fd5cfdae67 correctly points back via run_attempt_id to that attempt. Lineage is resolvable only in one direction (turn->attempt).",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT a.attempt_id, a.provider_turn_id, t.provider_turn_id FROM orchestration_v2_projection_run_attempts a JOIN orchestration_v2_projection_provider_turns t ON t.run_attempt_id=a.attempt_id WHERE a.thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415';\"",
|
||||
"sessionKey": "8ee00dcc-cursor-spacing"
|
||||
},
|
||||
{
|
||||
"title": "file_change diffStr has malformed diff headers (a//abs/path, b//abs/path)",
|
||||
"category": "other",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "turn-item:provider:cursor:native-item:tool_fee434e5-6388-483d-82f1-9e6c6ab418c (ordinal 1000042) payload diffStr begins '--- a//Users/julius/.t3/worktrees/codething-mvp/t3code-3cba2658/apps/mobile/src/features/home/HomeScreen.tsx' \u2014 absolute path concatenated after 'a/' yields double slash and a non-standard diff header; same for the other two file_change items (tool_361abe3b, tool_b586252d). Diff hunk content itself is intact (additions:2 deletions:1 recorded). Cosmetic, but breaks strict unified-diff parsers.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.diffStr'),1,80) FROM orchestration_v2_projection_turn_items WHERE thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND type='file_change';\"",
|
||||
"sessionKey": "8ee00dcc-cursor-spacing"
|
||||
},
|
||||
{
|
||||
"title": "Codex 'reasoning' items are silently dropped (no adapter handler, no projection)",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Surviving log window shows 45 item/started + 45 item/completed reasoning items for native thread 019f1b62-f532 (c878541b runs 4-6), but the projection has 0 reasoning-type turn_items for any of the four threads (types present: assistant_message, command_execution, file_change, user_message, checkpoint, dynamic_tool, run_interrupt_*). CodexAdapterV2.ts item/started / item/completed handlers dispatch on userMessage/commandExecution/mcpToolCall/dynamicToolCall/fileChange/webSearch/plan/collabAgentToolCall/subAgentActivity and fall through for 'reasoning' despite capabilities streamsReasoning:true (line 139). Mitigating: every observed reasoning item had empty summary/content (e.g. rs_0e493c0caf681939016a4539c1c0988193b7174c9c067dfdb2, summary:[], content:[]), so no user-visible text was actually lost in this session.",
|
||||
"repro": "cat ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep '\"decoded\"' | grep '\"item/completed\"' | grep '019f1b62' | grep -c '\"reasoning\"' vs SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='c878541b-a832-4757-a254-5550e3f6c2d1' AND type LIKE '%reason%';",
|
||||
"sessionKey": "codex-no-native-logs"
|
||||
},
|
||||
{
|
||||
"title": "contextCompaction native item has no projection representation",
|
||||
"category": "lost-data",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log shows item/completed contextCompaction id ad331e6d-f971-46a9-a04a-c70a1b86894f on turn 019f1e69-826e-7de2-9200-b6852ff53138 (c878541b run 4, ~16:00-16:05Z); no turn_item, node, or event for it exists (payload_json LIKE '%ompaction%' matches only incidental message text). Users cannot see that context was compacted mid-run. Native item carries only an id (no content), so the informational loss is small.",
|
||||
"repro": "grep 'contextCompaction' ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep 019f1b62",
|
||||
"sessionKey": "codex-no-native-logs"
|
||||
},
|
||||
{
|
||||
"title": "Run 119 marked failed while its native query kept running; retry run 120 adopted the result, leaving a duplicated user message",
|
||||
"category": "duplicate",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Run 119 failed at 2026-07-02T16:45:26.143Z (transport_error, ~1.5s after requested_at 16:45:24.618Z), but the native log shows query.open + prompt.offer at 16:45:25.921Z proceeding to SessionStart:resume (16:45:41) and a successful result at 16:47:00.764Z. Retry run 120 (requested 16:45:36.222Z) completed at 16:47:01.354Z with that assistant message (message:provider:claudeAgent:native-item:693d3576-4e56-4c10-9b0f-90ff9825f663, 3190 chars, intact). Two user messages with identical text exist: 9b135da3-dd1b-4a9a-90bc-ee4166bce48d (run 119) and 0f1b1078-74cb-4488-9626-e1ddbe933a9a (run 120) \u2014 timeline shows the prompt twice (plus the error item). Content preserved; cosmetic/duplication issue only.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT message_id, run_id, created_at FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at BETWEEN '2026-07-02T16:45' AND '2026-07-02T16:46'\"",
|
||||
"sessionKey": "71e29ba5-claude-mega"
|
||||
},
|
||||
{
|
||||
"title": "4 native error_during_execution results silently recovered in-adapter with no projection trace",
|
||||
"category": "error-handling",
|
||||
"severity": "low",
|
||||
"confidence": "medium",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native results with subtype=error_during_execution/is_error=true at 2026-07-02T01:34:23.046Z, 02:29:30.034Z, 05:08:27.090Z, 17:03:10.206Z fall inside runs 73/80/95/122 \u2014 all completed with a single run attempt and no error item/event. At 01:34:23 the error coincides with an outgoing prompt.offer (mid-stream steering) followed immediately by system init and continued streaming, so the adapter's transparent re-query is likely intentional; but the transient error is invisible to projections (debug info only in provider log).",
|
||||
"repro": "grep -h '\"subtype\":\"error_during_execution\"' ~/.t3/userdata-v2/logs/provider/71e29ba5*.log* | grep '\"stage\":\"decoded\"'",
|
||||
"sessionKey": "71e29ba5-claude-mega"
|
||||
},
|
||||
{
|
||||
"title": "Session has 7 subagent child threads, not 9 as briefed; all 7 fully linked and consistent",
|
||||
"category": "lineage",
|
||||
"severity": "low",
|
||||
"confidence": "high",
|
||||
"knownIssue": false,
|
||||
"evidence": "Native log contains exactly 7 top-level Agent tool_use spawns (toolu_01CtiEb3..., 01CrTuja..., 01TiUmm..., 01W2SNA..., 01RjCn6..., 017H3QK..., 018VQWh...); projections have 7 type='subagent' items, 7 orchestration_v2_projection_subagents rows all with non-null child_thread_id resolving to existing thread rows, and 7 child-thread event streams (79-260 events each) with items on the correct thread ids (0 items with mismatched threadId). The 2 failed subagents (task%3Aafbafdde..., task%3Aa0e0b5f3..., completed_at 2026-07-02T08:34:33.868Z) match native '[Request interrupted by user for tool use]' is_error tool_results for toolu_017H3QKcEb9FrecsT4tyzg1M / toolu_018VQWhHKSAP1cFkZwZGRGe5 at 08:34:33.867Z \u2014 correct failure surfacing, not a bug.",
|
||||
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_subagents WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016'\"",
|
||||
"sessionKey": "71e29ba5-claude-mega"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
# Plan: Orchestration V2 Session Audit Remediation
|
||||
|
||||
## Summary
|
||||
|
||||
A full audit of every v2 orchestrator session in `~/.t3/userdata-v2` (2026-07-02, 18 session
|
||||
groups, ~43k events, ~6.3k projected turn items, all 5 providers) compared native provider logs
|
||||
against ingested events and item projections. Core mechanics are healthy — zero stream_version
|
||||
gaps, zero ordinal collisions, positions table 100% consistent, no duplicate `nativeItemRef`s,
|
||||
no stuck non-terminal state — but 23 verified discrepancies cluster into the workstreams below.
|
||||
|
||||
Every finding was adversarially re-verified against the raw DB/logs and the adapter source.
|
||||
Repro commands are inline. File/line references are as of branch `t3code/codex-turn-mapping`
|
||||
on the audit date; expect drift.
|
||||
|
||||
Status legend: `[ ]` todo · `[~]` in progress · `[x]` done
|
||||
|
||||
## Tracking checklist
|
||||
|
||||
> **Restructure note (2026-07-04):** the PR stack was reorganized to combine with
|
||||
> mwolson's parallel work. Shared continuation plumbing (C0, ea57e97d58) now lives
|
||||
> directly on `t3code/codex-turn-mapping`; Claude session-continuity fixes including
|
||||
> our #1/#15 (+ fixtures `claude_result_is_error`, `claude_idle_resume`,
|
||||
> `advance_clock` step) live in PR #3860; grok/ACP lifecycle (superset of plan #7)
|
||||
> lives in PR #3578; this branch (PR #3677) keeps the remaining audit fixes:
|
||||
> #2 #3 #4 #5 #9 #10 #11 #12. Our turn.wakeup implementation was dropped in favor
|
||||
> of the C0 continuation design.
|
||||
|
||||
|
||||
- [x] 1. Honor `is_error` on Claude SDK results — MOVED to PR #3860 (with fixture claude_result_is_error)
|
||||
- [x] 2. Preserve real failure causes in projected errors (Claude adapter + ProviderFailure)
|
||||
- [x] 3. Preserve cursor failure detail (requestId, durationMs; SDK exposes no error text yet)
|
||||
- [x] 4. Log failure/lifecycle frames in native provider logs (claude + cursor runners)
|
||||
- [x] 5. Surface provider-process crashes / reconcile cancellations to the user
|
||||
- [x] 6. Ingest codex-native collab subagents — already implemented upstream (verified 2026-07-04 on #3908's branch: registerSubagentActivity/registerSubagentThreads handle subAgentActivity + collabAgentToolCall, and the subagent_v2 fixtures replay the exact a5a643b2 loss scenario incl. post-settle child completion, asserting the child's "Hello." result)
|
||||
- [ ] 7. Fix grok/ACP background subagent lifecycle + transcript projection
|
||||
- [x] 8. Invisible post-turn wakeup turns — SUPERSEDED by C0/#3860's provider-continuation design (our turn.wakeup implementation dropped in the restructure)
|
||||
- [x] 9. Route shared-codex-session native logs to the correct thread's file
|
||||
- [x] 10. Coalesce streaming-delta event persistence (~2800x amplification)
|
||||
- [x] 11. Assistant text segments merged without separator (fixed in worktree — add regression fixture)
|
||||
- [x] 12. OpenCode `file_search` items drop error/output
|
||||
- [ ] 13. Low-severity backlog (see section)
|
||||
- [ ] 14. Cursor SDK unhandled `write EPIPE` crashes the backend child (recurring, post-SDK-bump)
|
||||
|
||||
---
|
||||
|
||||
## 1. `is_error: true` on Claude SDK results ignored — failed runs recorded as completed
|
||||
|
||||
**Severity: high.** The Claude Agent SDK emits terminal `result` messages with
|
||||
`subtype: "success"` but `is_error: true` for API-level failures. The adapter only branches on
|
||||
subtype, so the run, run_attempt, provider_turn, and (for delegated tasks) the subagent row and
|
||||
the parent's `delegate_task` item all read `completed`.
|
||||
|
||||
Observed in four independent places:
|
||||
|
||||
- Delegated task `hello-opus-48` (thread `1156181e`): 401 auth failure, zero token usage,
|
||||
everything projected `completed`.
|
||||
- Same 401 in a5a643b2's run-4 delegated child — parent `delegate_task` item output.status
|
||||
`completed`.
|
||||
- Thread `47763f5e` run 1: 401 result projected as a completed run; error text survives only as
|
||||
a plain completed `assistant_message` (the SDK's synthetic `<synthetic>`-model message) — no
|
||||
error item, so the run reads as a success.
|
||||
- Thread `ea84f015` runs 11–13: `API Error: 529 Overloaded` (29 `api_retry` events preceding),
|
||||
all three runs `completed`.
|
||||
|
||||
**Root cause:** `ClaudeAdapterV2.ts` — `terminalStatusFromResult` (~line 1652) returns
|
||||
`"completed"` whenever `message.subtype === "success"`; the failure branch (~line 3254) only
|
||||
fires for non-success subtypes. `is_error` / `api_error_status` are never consulted.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. In `terminalStatusFromResult` (and the result handler), treat `subtype === "success" &&
|
||||
is_error === true` as a failure.
|
||||
2. Build a `ProviderFailure` from the result: `message` = the `result` text (e.g. `Failed to
|
||||
authenticate. API Error: 401 ...`), `code` = `api_error_status` when present, plausibly
|
||||
`retryable: true` for 429/529.
|
||||
3. Ensure a terminal-failure error item is emitted (not just the synthetic assistant message)
|
||||
and delegated-task subagent rows go to `failed`.
|
||||
4. Testkit: extend `ClaudeAdapterV2.testkit.ts` + replay fixtures with an
|
||||
`is_error`-on-success-subtype result.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';" # completed
|
||||
grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-*.log
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 2. Terminal failures persist only generic strings — root cause unrecoverable from DB
|
||||
|
||||
**Severity: high (systemic).** Every claudeAgent failed run in the DB persists exactly
|
||||
`{class: "transport_error", message: "Claude Agent SDK query failed.", code: null,
|
||||
retryable: null}` (threads 47763f5e run 10, 7f1dfff1 run 10, 71e29ba5 runs 89/119). The native
|
||||
log at those failure sites shows only the outgoing `query.open`/`prompt.offer` with nothing
|
||||
incoming — so after the fact, **no record of the actual failure exists anywhere**. The same
|
||||
pattern hit cursor (issue 3) — while codex proves it can be done right: codex failures keep the
|
||||
full upstream error body.
|
||||
|
||||
**Root causes:**
|
||||
|
||||
- `ClaudeAdapterV2.ts:279-281` — `ClaudeAgentSdkQueryRunnerError.message` getter hardcodes the
|
||||
string; the wrapped `cause` defect is discarded.
|
||||
- `ProviderFailure.ts:90-113` — `makeProviderFailure` reads only `.message`/`.code` off the
|
||||
squashed cause and never unwraps nested causes of tagged wrapper errors.
|
||||
- `RunExecutionService.ts:~830` — feeds `Cause.squash(cause)` into `makeProviderFailure`, so a
|
||||
tagged error's inner cause never reaches the projection. The server log printed the cause
|
||||
depth-elided (`failures: [ [Object] ]`), destroying the last copy.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Give wrapper errors (`ClaudeAgentSdkQueryRunnerError`, `ProviderAdapterTurnStartError` at
|
||||
`ProviderAdapter.ts:~291`) a message that includes `String(cause)` (or a `detail` field).
|
||||
2. In `makeProviderFailure`, walk the cause chain (`Cause.prettyErrors` / unwrap `.cause`) and
|
||||
persist a structured `detail` (message chain + code) on the failure payload; contracts change
|
||||
in `packages/contracts/src/orchestrationV2.ts` if the failure schema needs a `detail` field.
|
||||
3. Fix the server-log print to use full-depth inspection for causes.
|
||||
4. Side note from 47763f5e run 10: the failed `query.open` reused a **create-style `sessionId`
|
||||
param after the session had been closed** (retry with `resume:` succeeded) — check
|
||||
`ProviderSessionManager`/adapter open-vs-resume selection for closed sessions while fixing.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT thread_id, json_extract(payload_json,'$.failure.message') \
|
||||
FROM orchestration_v2_projection_turn_items WHERE type='error';"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 3. Cursor failure detail dropped (requestId, durationMs, SDK error_code)
|
||||
|
||||
**Severity: high.** Thread `c9e72a05` (the "why are cursor turns failing" session): run 2 failed
|
||||
after a 440s silent turn; native `run.completed` carried `status:"error"`,
|
||||
`requestId:"beca30c7-..."`, `durationMs:440732`. Projection kept only
|
||||
`{message: "Provider turn failed.", code: null}` — requestId and duration dropped. The real
|
||||
cause ("Authentication error. If you are logged in, try logging out and back in.") lives only in
|
||||
the Cursor SDK's local store (`runs.error_code`), which T3 never reads.
|
||||
|
||||
**Root cause:** `CursorAdapterV2.ts:2165-2168` maps `cause: (result as {error?: unknown}).error`
|
||||
— that field does not exist on the SDK `RunResult`, so it always falls back to
|
||||
`DEFAULT_PROVIDER_FAILURE_MESSAGE`.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Map what the result actually carries: persist `requestId` and `durationMs` on the failure
|
||||
payload (code field is a natural home for requestId).
|
||||
2. On `status === "error"`, query the Cursor SDK store for `runs.error_code` /
|
||||
error message for that run id and attach it.
|
||||
3. Note: verify against current SDK shape — the audit also found (refuted-as-intentional) cases
|
||||
where cursor's `run.completed` genuinely carries no detail; the fix is "persist everything
|
||||
present", not "invent detail".
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items \
|
||||
WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';"
|
||||
grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-*.log | tail -1
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 4. Native provider logs never record failure/lifecycle frames
|
||||
|
||||
**Severity: medium.** The "ground truth" logs cannot explain failed turns. In `721fc23c` the
|
||||
log ends with an outgoing `run.start` and no trace of the `agent.send` rejection 4ms later, nor
|
||||
of the provider child process fatally crashing (twice, `@cursor/sdk` Node error — visible only
|
||||
in `server-child.log`). No adapter has an error/lifecycle log kind at all.
|
||||
|
||||
**Root cause:** e.g. `CursorAgentSdk.ts` `send()` — log writes cover outgoing `run.start` and
|
||||
incoming frames only; `runnerError(cause, "run.start")` paths (lines ~408/440) write nothing.
|
||||
Process exit is not logged to the per-thread native log either.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Add an `error`/`lifecycle` kind to the native event logger contract and write a frame on:
|
||||
adapter send/open rejections, runner errors, provider process spawn/exit (with exit code),
|
||||
and turn-abort paths — across all adapters (cursor, claude, codex, ACP, opencode).
|
||||
2. Keep payloads small (message + code + native run/turn id), no secrets.
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 5. Provider crashes / reconcile cancellations are silent to the user
|
||||
|
||||
**Severity: high.** In `721fc23c` the cursor backend crashed mid-turn; startup reconcile
|
||||
cancelled run 1. In `48663fb7` a server restart orphaned the run; reconcile cancelled it. In
|
||||
both cases the user asked something, got **no response, no error item, and no explanation** —
|
||||
a reconcile-cancelled run is projected indistinguishably from a user cancellation.
|
||||
|
||||
**Root cause:** the startup runtime-reconcile (`command:runtime-reconcile:startup...`)
|
||||
terminalizes runs/attempts/turns to `cancelled` but emits no user-visible item and no reason.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. When reconcile terminalizes a run it did not start, emit an error (or `interrupted`) turn
|
||||
item with a reason: e.g. "Provider process exited unexpectedly" / "Run was interrupted by an
|
||||
app restart".
|
||||
2. Record the cancellation reason on the run payload (`cancelReason: "runtime_reconcile" |
|
||||
"user" | ...`) so UI and debugging can distinguish.
|
||||
3. Optional: auto-offer retry in UI for reconcile-cancelled runs.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT event_type, occurred_at FROM orchestration_events \
|
||||
WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%';"
|
||||
grep -n 'cursor/sdk\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 6. Codex-native collab subagents entirely missing from events and projections
|
||||
|
||||
**Severity: high (lost data).** In `a5a643b2` run 3 ("spawn a subagent"), codex spawned a
|
||||
native collab subagent: `subAgentActivity` item, `collabAgentToolCall` (`wait`), and a child
|
||||
native thread (`019f0c93-d260`) with webSearch, reasoning, and a final `agentMessage`
|
||||
("Hello."). **Zero** of it was ingested — no events, no items, no subagent row, no child
|
||||
thread. The child also completed *after* the parent turn finalized, so late-arriving child
|
||||
items need routing even post-turn.
|
||||
|
||||
**Root cause:** `CodexAdapterV2.ts` has no handlers for `subAgentActivity` /
|
||||
`collabAgentToolCall` item types, and events on non-primary native threads of the shared
|
||||
app-server session are not attributed to any T3 thread.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Handle `subAgentActivity`: create a subagent projection row + child provider thread (mirror
|
||||
of what `a61e9269`'s newer session shape already does — that session projected
|
||||
`subAgentActivity` fine, so check what differs: likely experimental collab API vs newer
|
||||
subagent API).
|
||||
2. Handle `collabAgentToolCall` as a tool item on the parent.
|
||||
3. Route child-native-thread items to the child T3 thread, including after the parent turn
|
||||
completed (same routing-loosening pattern used for owned-provider-thread updates in the
|
||||
wakeup work).
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%019f0c93-d260%';" # 0
|
||||
grep -c 'subAgentActivity\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-*.log # >0
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 7. Grok/ACP background subagent: wrong lifecycle + transcript never projected
|
||||
|
||||
**Severity: high (lost data) + medium (lifecycle).** Thread `5dcea72d` ("spawn a subagent"):
|
||||
|
||||
- The subagent row and parent `subagent` item were marked `completed` at spawn time
|
||||
(01:52:10) with the placeholder result "Subagent started in background..." — the task
|
||||
actually ran 75s (116 tool calls, per the later `TaskOutput` payload).
|
||||
- The child thread got only its 2 spawn-time items; the live transcript (811 decoded incoming
|
||||
ACP messages between runs) produced **zero** ingested events. The subagent's real final
|
||||
output never reached the child thread.
|
||||
|
||||
**Root cause:** `AcpAdapterV2.ts` `emitSubagent` (~lines 1047-1060) adopts the spawn tool's
|
||||
bootstrap text as the result and a non-running taskStatus as terminal; session notifications
|
||||
arriving **between runs** (no active turn) are dropped rather than buffered/routed to the
|
||||
subagent's child thread.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Keep the subagent `running` until a terminal task status; update result/completedAt from
|
||||
`TaskOutput` (or task-completion notification) when it arrives.
|
||||
2. Route/buffer ACP session notifications for background tasks outside active turns to the
|
||||
child thread (reuse the wakeup-buffer pattern from ClaudeAdapterV2 if applicable to ACP).
|
||||
3. Related low finding: child-thread items carry null `run_id`/`provider_thread_id`/
|
||||
`provider_turn_id` — populate lineage when projecting child items.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) \
|
||||
FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 8. Invisible post-turn wakeup turns (known — fix on this branch)
|
||||
|
||||
**Severity: high (lost data), known issue.** The audit quantified the pre-fix damage:
|
||||
|
||||
- `47763f5e`: 10 whole wakeup turns unpersisted — 16 assistant messages + 84 tool calls,
|
||||
including 5 real git pushes and the final "Converged. PR #3638 is fully green".
|
||||
- `ea84f015`: 42 tool calls + final assistant messages across 3 windows — including a GitHub
|
||||
comment posted with no user-visible record (`pull/2829#issuecomment-4861082710`).
|
||||
- `71e29ba5`: 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup), all falling
|
||||
in gaps between run windows, zero inside any run.
|
||||
|
||||
The fix (`turn.wakeup` / `ProviderWakeupService` / `attach_wakeup` / backgrounded-bash
|
||||
adoption) is implemented on `t3code/codex-turn-mapping`; these sessions ran on pre-fix builds.
|
||||
First `provider_wakeup` events in the DB appear 2026-07-01T22:47:41 — post-fix threads persist
|
||||
wakeups.
|
||||
|
||||
**Remaining work:**
|
||||
|
||||
- [x] Core fix implemented (this branch, replay fixture `claude_provider_wakeup`)
|
||||
- [ ] Sanity-check the three audit scenarios against the fixture set (task-notification wakeup,
|
||||
ScheduleWakeup sleep-loop, backgrounded Bash completion) — the audit evidence makes good
|
||||
additional fixture material
|
||||
- [ ] Known follow-ups (from memory): idle session reaper vs long sleeps; superseded-wakeup
|
||||
buffer only replays task bookkeeping; provider_turn has no `waiting` status literal
|
||||
|
||||
## 9. Shared codex session logs written to opener thread's file
|
||||
|
||||
**Severity: medium.** Four codex threads (`c878541b`, `de5f191a`, `68f7595b`, `af66fc2c`) have
|
||||
**no native log file at all** — their app-server traffic was written into
|
||||
`71e29ba5-...log.*` because that thread opened the shared codex app-server session.
|
||||
Consequence: rotation of the busy opener's log (10 files × 10MB) **destroyed the native ground
|
||||
truth** for most of those threads' runs; it also produced a false "ingestion gap" signal during
|
||||
the audit (another thread's traffic interleaved in 71e29ba5's log).
|
||||
|
||||
**Root cause:** `CodexAdapterV2.ts:~1136` — `codexAppServerClientFactoryFromSettingsLayer.open`
|
||||
builds `makeCodexAppServerProtocolLogger({ threadId: input.threadId })` once per app-server
|
||||
process; `EventNdjsonLogger.write` routes to `${threadSegment}.log` from that frozen threadId.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Resolve the log target per message, not per process: maintain a native-thread-id → T3
|
||||
thread-id map (the adapter already tracks owned native threads) and route each protocol
|
||||
frame to the owning thread's log; fall back to a shared
|
||||
`codex-shared-session.log` for unattributable frames (initialize, thread/start, etc.).
|
||||
2. Consider retention bump for provider logs, since they are the only ground truth
|
||||
(`.plans/06-provider-logstream-lifecycle.md` is the related prior art).
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # only 71e29ba5-*.log.{6,9,10}
|
||||
ls ~/.t3/userdata-v2/logs/provider/ | grep -c 'c878541b\|de5f191a\|68f7595b\|af66fc2c' # 0
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 10. Streaming deltas persisted as full-row event pairs (~2800x amplification)
|
||||
|
||||
**Severity: medium (cost/scale, not correctness).** Grok/ACP streams a child task's result
|
||||
per-token; each chunk is persisted as a **full-row** `turn-item.updated` + `message.updated`
|
||||
event pair. One 6,274-char result accumulated 2,704 events; a 2-minute session wrote 6,017
|
||||
rows (14% of the whole 43k-row table). Replay and projection costs scale with this.
|
||||
|
||||
**Root cause:** `AcpAdapterV2.emitSubagentAssistant` emits a full event pair per
|
||||
`agent_message_chunk`, and `ProviderEventIngestor` persists every emission.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Split live streaming from persistence: broadcast deltas to subscribers in-memory, persist
|
||||
coalesced snapshots (e.g. on item completion + every N seconds/K bytes while running).
|
||||
2. Alternatively debounce persistence per item id in the ingestor so any adapter gets the
|
||||
benefit.
|
||||
3. Check other adapters for the same pattern (claude/codex emit per-block, which is fine;
|
||||
ACP per-token is the outlier).
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT event_type, COUNT(*) FROM orchestration_events \
|
||||
WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 11. Claude assistant text segments merged without separator (fixed — needs regression fixture)
|
||||
|
||||
**Severity: medium, already fixed in worktree.** In the `6d618dc4` MCP group (build
|
||||
`fc23be8184`), 5 interleaved assistant text blocks were accumulated
|
||||
(`context.assistant.text += ...`) and emitted as ONE item at end of turn — 10,642 chars joined
|
||||
with no separator, ordered after all 19 tool calls, losing interleaving. Current worktree code
|
||||
(`emitAssistantTextArtifacts` per `message.uuid`) already emits per-segment items.
|
||||
|
||||
**Remaining work:**
|
||||
|
||||
- [x] Fix (already in worktree)
|
||||
- [ ] Add a replay fixture asserting multi-segment assistant text produces one item per SDK
|
||||
uuid, interleaved with tool items at correct ordinals
|
||||
|
||||
## 12. OpenCode `file_search` items drop error/output
|
||||
|
||||
**Severity: medium.** Child session `ses_0ea978228`: a failed `file_search` item projects only
|
||||
`{status: 'failed', type: 'file_search', pattern: '...'}` — the provider's error message is
|
||||
unrecoverable. Same shape drops successful read/grep/glob outputs (low finding).
|
||||
|
||||
**Root cause:** `OpenCodeAdapterV2.ts` — `toolOutput()` (line ~659) extracts
|
||||
`part.state.error`, but the `file_search` mapping branch (~line 1376) only maps `pattern`;
|
||||
output/error only attach for `dynamic_tool`. The contract type
|
||||
(`packages/contracts/src/orchestrationV2.ts` ~line 841) has no output/error field on
|
||||
`file_search` either.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Add optional `output`/`error` to the `file_search` item contract.
|
||||
2. Map `part.state.error` (and output where present) in the opencode/ACP `file_search` branch.
|
||||
3. Grok has the same gap (`file_search`/`read` persist only pattern/fileName echo — low
|
||||
finding); fix at the shared mapping level if possible.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT payload_json FROM orchestration_v2_projection_turn_items \
|
||||
WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## 13. Low-severity backlog
|
||||
|
||||
Unverified (single-auditor) findings, grouped. Tick when triaged/fixed:
|
||||
|
||||
**Lineage**
|
||||
- [ ] `run_attempts.provider_turn_id` is null on ALL 207 attempts DB-wide (reverse link only) —
|
||||
populate the forward link or drop the column
|
||||
- [ ] Opencode/claude "pending"-keyed provider-thread placeholder row persists alongside the
|
||||
real `ses_`-keyed row; runs/attempts reference one, items/active_provider_thread_id the
|
||||
other (3029dc85, 9f8d616d)
|
||||
- [ ] Subagent child-thread items carry null run/provider_thread/provider_turn ids (grok,
|
||||
ea84f015)
|
||||
- [ ] Interrupt-result turn item references an interrupt-request parent item that was never
|
||||
emitted (GLOBAL)
|
||||
- [ ] Synthesized terminal-failure error item references a provider_turn_id that was never
|
||||
projected (GLOBAL)
|
||||
|
||||
**Stuck state / lifecycle**
|
||||
- [ ] Projection ignores `provider-session.detached` — sessions stay `ready`/`running` for
|
||||
~20-25h until shutdown sweep (GLOBAL, 1156181e, 6d618dc4, 47763f5e, ea84f015); also
|
||||
claudeAgent sessions are never idle-reaped
|
||||
- [ ] Provider-thread row stayed `active` ~20h after its session stopped (9f8d616d)
|
||||
- [ ] Run 119 (71e29ba5) marked failed while its native query kept running; retry run 120
|
||||
adopted the result leaving a duplicated user message — dedupe/adopt semantics on retry
|
||||
|
||||
**Dropped provider data (no user-visible loss observed yet)**
|
||||
- [ ] Codex `reasoning` items silently dropped (no adapter handler; all observed summaries were
|
||||
empty — would lose data once codex emits populated summaries)
|
||||
- [ ] Codex `thread/tokenUsage/updated` + `account/rateLimits/updated` never ingested — runs
|
||||
have no usage data; cursor `run.completed` usage also dropped (8ee00dcc)
|
||||
- [ ] Codex `contextCompaction` item has no projection representation
|
||||
- [ ] Cursor tool calls that never returned natively are auto-marked `completed` with no
|
||||
results at turn end (c9e72a05) — should be `failed`/`interrupted`
|
||||
- [ ] 4 native `error_during_execution` results silently recovered in-adapter with no
|
||||
projection trace (71e29ba5); one absorbed during a steering message (ea84f015)
|
||||
|
||||
**Cosmetic / observability**
|
||||
- [ ] Grok + opencode native logs redact payloads to shape summaries — no content-level ground
|
||||
truth for audits; consider a debug setting to log content
|
||||
- [ ] Grok logs every successful `session/prompt` as `failed` with `errorTag: Interrupt`
|
||||
- [ ] Cursor native `read` tool calls projected as type `file_search` (semantic mismatch)
|
||||
- [ ] Cursor `file_change` diffStr has malformed headers (`a//abs/path`, `b//abs/path`)
|
||||
- [ ] 13 old backgrounded `local_bash` tasks projected as subagents with empty prompts and
|
||||
synthetic child threads (GLOBAL); backgrounded-bash child threads have empty-text prompt
|
||||
user_message items (7f1dfff1)
|
||||
- [ ] Cursor 7.3-minute silent hang before failing (c9e72a05) — no progress/heartbeat signal
|
||||
exists to distinguish a hung turn from a thinking one
|
||||
|
||||
## 14. Cursor SDK unhandled `write EPIPE` crashes the backend child (recurring)
|
||||
|
||||
**Severity: high.** Added 2026-07-02 after new cursor sessions reproduced backend crashes.
|
||||
Distinct from the June-29 crash that the `@cursor/sdk` version bump addressed.
|
||||
|
||||
Three occurrences in `server-child.log`, identical signature — `Unhandled 'error' event /
|
||||
Error: write EPIPE` on a `net.Socket`, followed by the `Node.js v24.15.0` footer (process
|
||||
death):
|
||||
|
||||
- **2026-07-02T19:04:57.558Z** — stack definitively inside `@cursor/sdk/dist/esm/357.js`
|
||||
(`et.execute` → `We.execute` → `Is.execute`): a connect-RPC execute writing to a
|
||||
cursor-agent socket whose far end had closed. Context: TWO cursor sessions streaming
|
||||
concurrently (d1bfdd3d run-0294b303, 4f3381e5 run-c7e93ba0, each with its own provider
|
||||
session, plus a native subagent task thread); both streamed token-deltas until 19:04:55.5.
|
||||
- **2026-07-01T20:47:34.573Z** and **2026-07-02T04:46:20.557Z** — same signature, but stack is
|
||||
only the async write-completion frame (`WriteWrap.onWriteComplete`), so origin unproven. No
|
||||
cursor turns were active; consistent with a lingering cursor-agent connection dying idle and
|
||||
a later write hitting EPIPE.
|
||||
|
||||
**Collateral (ties into issues 2/4/5):**
|
||||
|
||||
- d1bfdd3d run 1 + 4f3381e5 run 1 silently `cancelled` by startup reconcile at 19:05:01;
|
||||
4f3381e5 has NO error item at all (issue 5).
|
||||
- d1bfdd3d run 2 (retry) failed with the generic `Failed to start run ... on cursor provider
|
||||
thread ...pending...` wrapper, cause depth-elided in the log (issue 2), and targeted the
|
||||
stale `pending`-keyed provider thread (issue 13 lineage note).
|
||||
- The two earlier EPIPE crashes explain two previously "undebuggable" audit failures: the
|
||||
restarted child killed the live claude CLI processes, so 7f1dfff1 run 10 (requested
|
||||
20:47:56, `claude-query-stream-failed` 20:47:58) and 71e29ba5 run 89 (requested 04:47:03)
|
||||
failed ~20-40s after each crash with the generic "Claude Agent SDK query failed."
|
||||
- The June-29 crash's actual error text is unknowable: the stderr dump was truncated at
|
||||
51,674 chars (log line cap) BEFORE the error message — only minified bundle source survived.
|
||||
|
||||
**Proposed fix:**
|
||||
|
||||
1. Containment: attach `error` handlers to (or wrap) the cursor SDK's sockets, and add a
|
||||
`process.on('uncaughtException'/'unhandledRejection')` policy in the backend child that
|
||||
fails the owning provider session instead of dying. Longer-term: isolate provider SDKs in
|
||||
their own child process so an SDK crash cannot kill the orchestrator.
|
||||
2. Report upstream to Cursor: SDK leaves its agent socket without an `error` listener;
|
||||
`write EPIPE` after agent-process exit is fatal to the host.
|
||||
3. Fix stderr log truncation: when capping captured child output, keep the TAIL (where Node
|
||||
prints the error + stack), not just the head.
|
||||
4. Issues 2/4/5 remain the reason this was hard to diagnose — they get us error items with
|
||||
real causes, native-log failure frames, and user-visible reconcile cancellations.
|
||||
|
||||
**Repro:**
|
||||
|
||||
```sh
|
||||
grep -n "Unhandled 'error' event" ~/.t3/userdata-v2/logs/server-child.log # 3 hits
|
||||
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
|
||||
"SELECT run_id,status,completed_at FROM orchestration_v2_projection_runs \
|
||||
WHERE thread_id IN ('d1bfdd3d-38cc-4ff3-ab75-8be6dc592b00','4f3381e5-89e2-45a8-bca1-bbe5d520bbba');"
|
||||
```
|
||||
|
||||
- [ ] Status: not started
|
||||
|
||||
## Refuted during verification (do NOT act on)
|
||||
|
||||
- 71e29ba5 "ingestion gap, 119 items lost" — traffic belonged to c878541b via the shared codex
|
||||
session (see issue 9).
|
||||
- 47763f5e "122 thinking blocks dropped" — all native thinking blocks were empty
|
||||
(`{"thinking":""}`); nothing to lose. (Reasoning ingestion is still absent, tracked as low.)
|
||||
- ea84f015 failed cursor runs 15-17 "generic error" — native results genuinely carried no
|
||||
detail; nothing to persist (but see issues 3/4 for making cursor carry detail).
|
||||
|
||||
## Validation
|
||||
|
||||
- Re-run the audit repro queries above after each fix; each issue's repro should flip.
|
||||
- Extend replay fixtures (`testkit/fixtures/`) per issue where marked; the audit evidence
|
||||
(thread ids + native log excerpts) is fixture source material.
|
||||
- Full audit data with per-finding evidence, verifier verdicts, and repro commands:
|
||||
`.plans/22-orchestration-v2-audit-findings.json`.
|
||||
@@ -10,3 +10,6 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
21. `21-orchestration-v2-application-integration.md`
|
||||
@@ -0,0 +1,89 @@
|
||||
# Replace React Query With AtomRpc + Atom State
|
||||
|
||||
## Summary
|
||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
||||
- Keep Zustand for orchestration read model and UI state.
|
||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
||||
|
||||
## Target Architecture
|
||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
||||
|
||||
## Phase 1: Infrastructure First
|
||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
||||
2. Build the AtomRpc client on top of that layer.
|
||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
||||
5. Land this as a no-behavior-change PR.
|
||||
|
||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
||||
|
||||
## Phase 3: Replace React Query Domain By Domain
|
||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
||||
6. Defer the desktop updater until the last phase.
|
||||
|
||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
||||
2. Keep Zustand orchestration/event application unchanged.
|
||||
3. Map current effects exactly:
|
||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
||||
- file creation/deletion/restoration touches `project:${cwd}`
|
||||
- config-affecting server events touch `server-config`
|
||||
|
||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
||||
1. Create narrow modules instead of a replacement mega-facade:
|
||||
- `rpc/orchestrationActions.ts`
|
||||
- `rpc/terminalActions.ts`
|
||||
- `rpc/gitActions.ts`
|
||||
- `rpc/projectActions.ts`
|
||||
- `platform/desktopBridge.ts`
|
||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
||||
|
||||
## Phase 6: Remove React Query Completely
|
||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
||||
4. Delete the old query-option tests.
|
||||
|
||||
## Public Interfaces And Types
|
||||
- Preserve the current server-state hook names during the transition.
|
||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
||||
- Do not expose raw AtomRpc clients to components.
|
||||
- Do not add Suspense as part of this migration.
|
||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
||||
|
||||
## Test Plan
|
||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
||||
- Acceptance scenarios:
|
||||
- welcome still bootstraps snapshot and navigation
|
||||
- keybindings toast still responds to config stream updates
|
||||
- git status/branches refresh after checkout/pull/worktree actions
|
||||
- PR resolve dialog keeps cached result while typing
|
||||
- `@` path search refreshes after file mutations and orchestration events
|
||||
- diff panel refreshes when checkpoints arrive
|
||||
- desktop updater still reflects push events and button actions
|
||||
|
||||
## Assumptions And Defaults
|
||||
- Zustand stays in scope; only `react-query` is being removed.
|
||||
- `desktopBridge` remains the only non-RPC boundary.
|
||||
- The migration lands as 5-6 small PRs, each green independently.
|
||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
||||
@@ -0,0 +1,252 @@
|
||||
# Spec 1:1 Cutover Plan
|
||||
|
||||
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
|
||||
|
||||
Execution mode for this plan:
|
||||
|
||||
- Hard cutover only. Existing DB and migration history are disposable.
|
||||
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
|
||||
- We optimize for small, reviewable work units, not continuous app operability.
|
||||
- Only the final gate requires everything to run cleanly.
|
||||
|
||||
## 1. Freeze SPEC contract as source of truth
|
||||
|
||||
Work units:
|
||||
|
||||
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.
|
||||
- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.
|
||||
- Add app-level requirements per row: writer path, reader path, and owning module.
|
||||
- Mark each row with status labels: `required`, `implemented`, `to-replace`, `delete`.
|
||||
- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Complete matrix file with no unclassified rows.
|
||||
- Single source checklist used by all later steps.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- No code changes required yet.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Every requirement in `7.1`-`7.4` has exactly one matrix row.
|
||||
|
||||
## 2. Hard cutover migrations (replace current migration set)
|
||||
|
||||
Work units:
|
||||
|
||||
- Delete the current legacy migration files and rewrite migration loader ordering.
|
||||
- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.
|
||||
- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.
|
||||
- Create `003_checkpoint_diff_blobs.ts` with uniqueness on `(thread_id, from_turn_count, to_turn_count)`.
|
||||
- Create `004_provider_session_runtime.ts` with PK and runtime lookup indexes.
|
||||
- Create `005_projections.ts` with all projection tables:
|
||||
- `projection_projects`
|
||||
- `projection_threads`
|
||||
- `projection_thread_messages`
|
||||
- `projection_thread_activities`
|
||||
- `projection_thread_sessions`
|
||||
- `projection_thread_turns`
|
||||
- `projection_checkpoints`
|
||||
- `projection_pending_approvals`
|
||||
- `projection_state`
|
||||
- Add all required indexes/constraints in `005_projections.ts`.
|
||||
- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- New 5-file migration chain.
|
||||
- Updated migration loader references only new migrations.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Repositories/services can be temporarily broken due to removed old tables.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Fresh DB initializes with only canonical tables plus migration bookkeeping.
|
||||
|
||||
## 3. Align persistence row/request schemas to DB 1:1
|
||||
|
||||
Work units:
|
||||
|
||||
- Define row schemas for each canonical table (contracts or persistence layer module).
|
||||
- Define request schemas for every insert/update/query operation touching canonical tables.
|
||||
- Remove or deprecate row/request schemas tied to deleted legacy tables.
|
||||
- Normalize enum and null semantics to match contracts exactly.
|
||||
- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Canonical row/request schemas committed.
|
||||
- Zero references to legacy row schemas in active code paths.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Runtime can still fail while query layers are being rewired.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Every canonical table used in code has a typed row schema and typed request schema.
|
||||
|
||||
## 4. Rewrite event store for full persisted envelope
|
||||
|
||||
Work units:
|
||||
|
||||
- Refactor append path to write full envelope fields:
|
||||
- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`
|
||||
- Implement stream version assignment/checking per aggregate stream.
|
||||
- Refactor read/replay path to decode payload and metadata from JSON and return `OrchestrationEvent` consistently.
|
||||
- Remove assumptions from old minimal schema (`aggregate_id`, missing metadata/actor).
|
||||
- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Event store append/replay fully aligned with canonical envelope.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Command dispatch flow can be partially broken until receipts/projectors are updated.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Event store no longer depends on legacy event table shape.
|
||||
|
||||
## 5. Add command receipt idempotency
|
||||
|
||||
Work units:
|
||||
|
||||
- Introduce persistence access layer for `orchestration_command_receipts`.
|
||||
- In command dispatch flow, check existing receipt by `commandId` before append.
|
||||
- On first execution, persist accepted receipt with `resultSequence`.
|
||||
- On domain rejection, persist rejected receipt with error payload.
|
||||
- On duplicate command, return prior result from receipt without re-appending event.
|
||||
- Ensure receipt write and event append ordering is deterministic.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Dispatch path with idempotency behavior wired through receipts.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Snapshot/read model may still be inconsistent until projectors are fully wired.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Duplicate command IDs no longer create duplicate events.
|
||||
|
||||
## 6. Build DB-backed projection pipeline
|
||||
|
||||
Work units:
|
||||
|
||||
- Create projector runner that consumes events and applies table-specific projections.
|
||||
- Implement projector handlers for each projection table.
|
||||
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.
|
||||
- Define projector names used in `projection_state` and make them stable constants.
|
||||
- Add replay bootstrap from event store to bring projections up to latest sequence on startup.
|
||||
- Add safe resume logic from projector `last_applied_sequence`.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Persistent projector pipeline writing all `projection_*` tables.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Web/API layer may still read old in-memory model until step 7.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Events drive projection rows in DB; projection state advances transactionally.
|
||||
|
||||
## 7. Move RPC reads to projections and diff blobs
|
||||
|
||||
Work units:
|
||||
|
||||
- Implement snapshot query service reading only projection tables.
|
||||
- Build thread hydration from projection rows: messages, activities, checkpoints, session.
|
||||
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.
|
||||
- Implement `getTurnDiff` query backed by `checkpoint_diff_blobs` only.
|
||||
- Remove or bypass in-memory snapshot construction for RPC responses.
|
||||
- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Provider runtime persistence may still be partially legacy until step 8.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- No orchestration read RPC depends on legacy tables or in-memory-only state.
|
||||
|
||||
## 8. Migrate provider runtime persistence to canonical table
|
||||
|
||||
Work units:
|
||||
|
||||
- Create repository/service for `provider_session_runtime`.
|
||||
- Update adapter/session manager to persist runtime/resume cursor in new table.
|
||||
- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.
|
||||
- Remove writes to legacy provider session tables.
|
||||
- Verify restart/resume path reads runtime state from canonical table only.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Provider runtime state entirely backed by `provider_session_runtime`.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Some legacy interfaces may still exist but should be disconnected.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- Runtime restore no longer reads/writes legacy provider session persistence.
|
||||
|
||||
## 9. Remove old cruft aggressively
|
||||
|
||||
Work units:
|
||||
|
||||
- Delete legacy repositories/services that map to removed tables.
|
||||
- Remove dead migration imports and obsolete persistence service interfaces.
|
||||
- Remove compatibility code paths that translate legacy row shapes.
|
||||
- Remove unused contracts/types linked to deprecated persistence model.
|
||||
- Update internal docs/comments to reference canonical projection/event model only.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Legacy persistence and translation layers removed from active codebase.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- Temporary compile failures acceptable while deletion/refactor is in progress.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- No production code path references deleted legacy tables/services.
|
||||
|
||||
## 10. Final verification gate (first point where green is required)
|
||||
|
||||
Work units:
|
||||
|
||||
- Add migration tests that assert canonical tables, columns, constraints, and indexes.
|
||||
- Add event store tests for envelope persistence, metadata, actor kind, and replay.
|
||||
- Add receipt idempotency tests for accept/reject/duplicate paths.
|
||||
- Add projector tests for transactional row updates + `projection_state` updates.
|
||||
- Add snapshot tests verifying projection-sourced output and `snapshotSequence` semantics.
|
||||
- Add turn diff tests verifying `checkpoint_diff_blobs` source of truth.
|
||||
- Add provider runtime tests for persist + restart + resume behavior.
|
||||
- Run project lint/typecheck/tests and fix failures.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Green checks with canonical schema + persistence model in place.
|
||||
|
||||
Breakage allowed:
|
||||
|
||||
- None at end of step.
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.
|
||||
@@ -0,0 +1,433 @@
|
||||
# SPEC Contract Matrix (Sections 7.1-7.4)
|
||||
|
||||
Status legend:
|
||||
|
||||
- `required`: requirement acknowledged, no current implementation claim yet.
|
||||
- `implemented`: requirement currently satisfied in code + schema.
|
||||
- `to-replace`: partial/misaligned implementation exists and must be replaced.
|
||||
- `delete`: current path actively conflicts with SPEC and should be removed.
|
||||
|
||||
## 7.1 Write-Side Persisted Tables
|
||||
|
||||
### W1
|
||||
|
||||
- Spec ref: `7.1.1 orchestration_events`
|
||||
- Requirement: append-only event store with canonical envelope columns.
|
||||
- SQL contract:
|
||||
- `sequence INTEGER PRIMARY KEY` (global monotonic)
|
||||
- `event_id TEXT UNIQUE NOT NULL`
|
||||
- `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')`
|
||||
- `stream_id TEXT NOT NULL`
|
||||
- `stream_version INTEGER NOT NULL`
|
||||
- `event_type TEXT NOT NULL`
|
||||
- `occurred_at TEXT NOT NULL`
|
||||
- `command_id TEXT NULL`
|
||||
- `causation_event_id TEXT NULL`
|
||||
- `correlation_id TEXT NULL`
|
||||
- `actor_kind TEXT NOT NULL CHECK IN ('client','server','provider')`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `metadata_json TEXT NOT NULL`
|
||||
- Current writer path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts`
|
||||
- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts`
|
||||
- Owner module: `apps/server/src/persistence` (event store + migrations)
|
||||
- Status: `to-replace`
|
||||
- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
|
||||
|
||||
### W2
|
||||
|
||||
- Spec ref: `7.1.2 orchestration_command_receipts`
|
||||
- Requirement: command idempotency + ack replay receipts table.
|
||||
- SQL contract:
|
||||
- `command_id TEXT PRIMARY KEY`
|
||||
- `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')`
|
||||
- `aggregate_id TEXT NOT NULL`
|
||||
- `accepted_at TEXT NOT NULL`
|
||||
- `result_sequence INTEGER NOT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('accepted','rejected')`
|
||||
- `error TEXT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: `apps/server/src/orchestration` dispatch boundary + `apps/server/src/persistence`
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and missing idempotency flow.
|
||||
|
||||
### W3
|
||||
|
||||
- Spec ref: `7.1.3 checkpoint_diff_blobs`
|
||||
- Requirement: store large plaintext diffs separate from checkpoint summaries.
|
||||
- SQL contract:
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `from_turn_count INTEGER NOT NULL`
|
||||
- `to_turn_count INTEGER NOT NULL`
|
||||
- `diff TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `UNIQUE(thread_id, from_turn_count, to_turn_count)`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: `apps/server/src/persistence` + turn diff query service
|
||||
- Status: `to-replace`
|
||||
- Notes: no canonical diff blob table yet.
|
||||
|
||||
### W4
|
||||
|
||||
- Spec ref: `7.1.4 provider_session_runtime`
|
||||
- Requirement: server-internal provider runtime/resume state.
|
||||
- SQL contract:
|
||||
- `provider_session_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `provider_name TEXT NOT NULL`
|
||||
- `adapter_key TEXT NOT NULL`
|
||||
- `provider_thread_id TEXT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('starting','running','stopped','error')`
|
||||
- `last_seen_at TEXT NOT NULL`
|
||||
- `resume_cursor_json TEXT NULL`
|
||||
- `runtime_payload_json TEXT NULL`
|
||||
- Current writer path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`)
|
||||
- Current reader path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`)
|
||||
- Owner module: provider runtime manager + persistence runtime repository
|
||||
- Status: `to-replace`
|
||||
- Notes: existing `provider_sessions` schema is incompatible and too small.
|
||||
|
||||
## 7.2 Canonical Persisted Event Schema
|
||||
|
||||
### E1
|
||||
|
||||
- Spec ref: `7.2 OrchestrationPersistedEventSchema`
|
||||
- Requirement: full typed persisted event envelope in shared contracts.
|
||||
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.
|
||||
- Current writer path: contracts defined in `packages/contracts/src/orchestration.ts`
|
||||
- Current reader path: used by persistence decode boundaries (partial)
|
||||
- Owner module: `packages/contracts`
|
||||
- Status: `implemented`
|
||||
- Notes: contract schema exists; DB + store mapping still incomplete.
|
||||
|
||||
### E2
|
||||
|
||||
- Spec ref: `7.2 Rules/payload discriminated by eventType`
|
||||
- Requirement: `payload` validation keyed by `eventType`.
|
||||
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.
|
||||
- Current writer path: `packages/contracts/src/orchestration.ts`
|
||||
- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts` decode path
|
||||
- Owner module: contracts + event store
|
||||
- Status: `to-replace`
|
||||
- Notes: decode is present but DB does not persist full envelope columns.
|
||||
|
||||
### E3
|
||||
|
||||
- Spec ref: `7.2 Rules/provider ids scope`
|
||||
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.
|
||||
- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.
|
||||
- Current writer path: `apps/server/src/orchestration/decider.ts` (metadata mostly empty)
|
||||
- Current reader path: projector/event consumers
|
||||
- Owner module: decider + provider ingestion + event store
|
||||
- Status: `to-replace`
|
||||
- Notes: metadata plumbing is incomplete in persistence path.
|
||||
|
||||
### E4
|
||||
|
||||
- Spec ref: `7.2 Rules/streamVersion concurrency guard`
|
||||
- Requirement: stream version monotonic per aggregate stream; enforced on write.
|
||||
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: event store append logic + DB constraints
|
||||
- Status: `to-replace`
|
||||
- Notes: no stream version assignment/checking today.
|
||||
|
||||
## 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
### P1
|
||||
|
||||
- Spec ref: `7.3.1 projection_projects`
|
||||
- Requirement: persisted project projection table.
|
||||
- SQL contract:
|
||||
- `project_id TEXT PRIMARY KEY`
|
||||
- `title TEXT NOT NULL`
|
||||
- `workspace_root TEXT NOT NULL`
|
||||
- `default_model TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `deleted_at TEXT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
|
||||
|
||||
### P2
|
||||
|
||||
- Spec ref: `7.3.2 projection_threads`
|
||||
- Requirement: persisted thread projection table.
|
||||
- SQL contract:
|
||||
- `thread_id TEXT PRIMARY KEY`
|
||||
- `project_id TEXT NOT NULL`
|
||||
- `title TEXT NOT NULL`
|
||||
- `model TEXT NOT NULL`
|
||||
- `branch TEXT NULL`
|
||||
- `worktree_path TEXT NULL`
|
||||
- `latest_turn_id TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `deleted_at TEXT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projector writes.
|
||||
|
||||
### P3
|
||||
|
||||
- Spec ref: `7.3.3 projection_thread_messages`
|
||||
- Requirement: persisted thread message projection table.
|
||||
- SQL contract:
|
||||
- `message_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `role TEXT NOT NULL CHECK IN ('user','assistant','system')`
|
||||
- `text TEXT NOT NULL`
|
||||
- `is_streaming INTEGER/BOOLEAN NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and message projection writes.
|
||||
|
||||
### P4
|
||||
|
||||
- Spec ref: `7.3.4 projection_thread_activities`
|
||||
- Requirement: persisted thread activity projection table.
|
||||
- SQL contract:
|
||||
- `activity_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `tone TEXT NOT NULL CHECK IN ('info','tool','approval','error')`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `summary TEXT NOT NULL`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: no canonical activity projection persistence.
|
||||
|
||||
### P5
|
||||
|
||||
- Spec ref: `7.3.5 projection_thread_sessions`
|
||||
- Requirement: persisted thread session projection table.
|
||||
- SQL contract:
|
||||
- `thread_id TEXT PRIMARY KEY`
|
||||
- `status TEXT NOT NULL CHECK IN ('idle','starting','running','ready','interrupted','stopped','error')`
|
||||
- `provider_name TEXT NULL`
|
||||
- `provider_session_id TEXT NULL`
|
||||
- `provider_thread_id TEXT NULL`
|
||||
- `active_turn_id TEXT NULL`
|
||||
- `last_error TEXT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: current provider session table is not this domain projection.
|
||||
|
||||
### P6
|
||||
|
||||
- Spec ref: `7.3.6 projection_thread_turns`
|
||||
- Requirement: persisted thread turn projection table.
|
||||
- SQL contract:
|
||||
- `turn_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_count INTEGER NOT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('running','completed','interrupted','error')`
|
||||
- `user_message_id TEXT NULL`
|
||||
- `assistant_message_id TEXT NULL`
|
||||
- `started_at TEXT NOT NULL`
|
||||
- `completed_at TEXT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector pipeline + session/turn query helpers
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projection logic.
|
||||
|
||||
### P7
|
||||
|
||||
- Spec ref: `7.3.7 projection_checkpoints`
|
||||
- Requirement: persisted checkpoint summary projection table.
|
||||
- SQL contract:
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NOT NULL`
|
||||
- `checkpoint_turn_count INTEGER NOT NULL`
|
||||
- `checkpoint_ref TEXT NOT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('ready','missing','error')`
|
||||
- `files_json TEXT NOT NULL`
|
||||
- `assistant_message_id TEXT NULL`
|
||||
- `completed_at TEXT NOT NULL`
|
||||
- `UNIQUE(thread_id, checkpoint_turn_count)`
|
||||
- Current writer path: legacy `provider_checkpoints` writes in `apps/server/src/persistence/Layers/Checkpoints.ts`
|
||||
- Current reader path: legacy checkpoint repository
|
||||
- Owner module: projector pipeline + checkpoint query layer
|
||||
- Status: `to-replace`
|
||||
- Notes: current table semantics do not match canonical checkpoint projection schema.
|
||||
|
||||
### P8
|
||||
|
||||
- Spec ref: `7.3.8 projection_pending_approvals`
|
||||
- Requirement: persisted pending-approval projection table.
|
||||
- SQL contract:
|
||||
- `request_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('pending','resolved')`
|
||||
- `decision TEXT NULL CHECK IN ('accept','acceptForSession','decline','cancel')`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `resolved_at TEXT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector pipeline + approval query layer
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projection logic.
|
||||
|
||||
### P9
|
||||
|
||||
- Spec ref: `7.3.9 projection_state`
|
||||
- Requirement: projector progress tracking table.
|
||||
- SQL contract:
|
||||
- `projector TEXT PRIMARY KEY`
|
||||
- `last_applied_sequence INTEGER NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector runner/checkpointing
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projector bookkeeping.
|
||||
|
||||
### P10
|
||||
|
||||
- Spec ref: `7.3 Projection consistency rules`
|
||||
- Requirement: projector row updates and `projection_state` update must be atomic per event.
|
||||
- SQL contract: per-projector transaction boundary covering both projection write and state update.
|
||||
- Current writer path: none (in-memory projector has no SQL transaction)
|
||||
- Current reader path: none
|
||||
- Owner module: projector runner
|
||||
- Status: `to-replace`
|
||||
- Notes: requires transactional projection executor.
|
||||
|
||||
### P11
|
||||
|
||||
- Spec ref: `7.3 Optional debug field`
|
||||
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
|
||||
- SQL contract: optional; not required in baseline schema.
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector runner
|
||||
- Status: `required`
|
||||
- Notes: interpretation: exclude from first cutover unless debugging requires it.
|
||||
|
||||
## 7.4 Snapshot and RPC Requirements
|
||||
|
||||
### R1
|
||||
|
||||
- Spec ref: `7.4.1`
|
||||
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
|
||||
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.
|
||||
- Current writer path: in-memory model built in `apps/server/src/orchestration/projector.ts`
|
||||
- Current reader path: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts#getReadModel`
|
||||
- Owner module: snapshot query service + ws RPC handler
|
||||
- Status: `delete`
|
||||
- Notes: current in-memory read model path must be removed for SPEC compliance.
|
||||
|
||||
### R2
|
||||
|
||||
- Spec ref: `7.4.2`
|
||||
- Requirement: snapshot `projects[]` source is `projection_projects`.
|
||||
- SQL contract: `projects` collection assembled from `projection_projects` rows.
|
||||
- Current writer path: none
|
||||
- Current reader path: in-memory thread/project arrays
|
||||
- Owner module: snapshot query service
|
||||
- Status: `to-replace`
|
||||
- Notes: no DB project projection reader exists yet.
|
||||
|
||||
### R3
|
||||
|
||||
- Spec ref: `7.4.3`
|
||||
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
|
||||
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.
|
||||
- Current writer path: legacy checkpoint repo data model
|
||||
- Current reader path: in-memory checkpoints from orchestration events
|
||||
- Owner module: snapshot query service + checkpoint projector
|
||||
- Status: `to-replace`
|
||||
- Notes: canonical projection table and reader not implemented.
|
||||
|
||||
### R4
|
||||
|
||||
- Spec ref: `7.4.4`
|
||||
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
|
||||
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
|
||||
- Current writer path: none for diff blobs
|
||||
- Current reader path: `orchestration.getTurnDiff` schema exists, data backing incomplete
|
||||
- Owner module: ws RPC handler + diff query service
|
||||
- Status: `to-replace`
|
||||
- Notes: current checkpoint repository is not canonical source.
|
||||
|
||||
### R5
|
||||
|
||||
- Spec ref: `7.4.5`
|
||||
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
|
||||
- SQL contract: session lookup by `thread_id` from projection table.
|
||||
- Current writer path: mixed provider/session handling paths
|
||||
- Current reader path: legacy provider session persistence lookups
|
||||
- Owner module: provider dispatch/session resolution
|
||||
- Status: `to-replace`
|
||||
- Notes: remove provider-session-as-routing-key behavior.
|
||||
|
||||
### R6
|
||||
|
||||
- Spec ref: `7.4.6`
|
||||
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
|
||||
- SQL contract: `MIN(last_applied_sequence)` across required projector keys.
|
||||
- Current writer path: none
|
||||
- Current reader path: currently from in-memory event projection sequence
|
||||
- Owner module: snapshot query service
|
||||
- Status: `to-replace`
|
||||
- Notes: must move from in-memory sequence to DB projection-state semantics.
|
||||
|
||||
### R7
|
||||
|
||||
- Spec ref: `7.4.7`
|
||||
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).
|
||||
- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.
|
||||
- Current writer path: event stream via `OrchestrationEventStore.readFromSequence`
|
||||
- Current reader path: ws replay flow in `apps/server/src/wsServer.ts`
|
||||
- Owner module: ws RPC + event stream handoff layer
|
||||
- Status: `to-replace`
|
||||
- Notes: interpretation requires explicit consistency boundary (transaction, sequence fence, or equivalent).
|
||||
|
||||
## Ambiguous/Interpretation Decisions (tracked upfront)
|
||||
|
||||
### A1
|
||||
|
||||
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
|
||||
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
|
||||
|
||||
### A2
|
||||
|
||||
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
|
||||
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
|
||||
|
||||
### A3
|
||||
|
||||
- Topic: `snapshotSequence` dependency set for min-sequence computation.
|
||||
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
|
||||
|
||||
### A4
|
||||
|
||||
- Topic: no-gap handoff mechanism in `7.4.7`.
|
||||
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
|
||||
|
||||
## Checklist Completeness Statement
|
||||
|
||||
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
|
||||
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
|
||||
- Unclassified rows: `0`.
|
||||
@@ -0,0 +1 @@
|
||||
alchemy/test/**
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
name: Deploy Website
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "website/**"
|
||||
- "packages/alchemy/**"
|
||||
- "bun.lock"
|
||||
- ".github/workflows/deploy.yml"
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- synchronize
|
||||
- closed
|
||||
paths:
|
||||
- "website/**"
|
||||
- "packages/alchemy/**"
|
||||
- "bun.lock"
|
||||
- ".github/workflows/deploy.yml"
|
||||
|
||||
concurrency:
|
||||
group: deploy-website-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}',
|
||||
github.event.number) || (github.ref == 'refs/heads/main' && 'prod' ||
|
||||
github.ref_name) }}
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: ${{ github.event.action != 'closed' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
# Mint a token for the alchemy-version-bot GitHub App so the PR
|
||||
# preview comment (created via GitHub.Comment in alchemy.run.ts)
|
||||
# posts under the bot's identity instead of `github-actions[bot]`.
|
||||
# Same App as release.yml — its installation scopes already cover
|
||||
# PR comments.
|
||||
- name: Generate bot token
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
# Build the website ahead of `alchemy deploy`. The
|
||||
# Cloudflare.StaticSite resource declares the same `bun run build`
|
||||
# in its config and runs it as part of the create lifecycle, but
|
||||
# on update plans alchemy reads `dist/` during plan.diff before
|
||||
# the embedded Build resource gets a chance to (re)run, causing
|
||||
# a NotFound on a fresh CI checkout. Building here makes the
|
||||
# workflow correct under both create and update plans.
|
||||
- name: Build website
|
||||
working-directory: website
|
||||
run: bun run build
|
||||
|
||||
- name: Deploy
|
||||
working-directory: website
|
||||
run: bun alchemy deploy --stage ${{ env.STAGE }} --yes
|
||||
env:
|
||||
# Alchemy's Cloudflare auth provider accepts either a scoped
|
||||
# API token (CLOUDFLARE_API_TOKEN) or the legacy global API
|
||||
# key paired with email (CLOUDFLARE_API_KEY +
|
||||
# CLOUDFLARE_EMAIL). We use the latter here so CI matches
|
||||
# the credentials in Doppler / .env, where only the admin
|
||||
# global key is provisioned.
|
||||
CLOUDFLARE_API_KEY: ${{ secrets.ADMIN_CLOUDFLARE_API_KEY }}
|
||||
CLOUDFLARE_EMAIL: ${{ secrets.ADMIN_CLOUDFLARE_EMAIL }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ env.STAGE == 'prod' &&
|
||||
secrets.PROD_CLOUDFLARE_ACCOUNT_ID ||
|
||||
secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
|
||||
PULL_REQUEST: ${{ github.event.number }}
|
||||
# On `pull_request` events GitHub Actions' built-in
|
||||
# `GITHUB_SHA` is the synthetic merge commit (PR head merged
|
||||
# into base) — that SHA never shows up in the PR's git log.
|
||||
# `GITHUB_SHA` is also a reserved env var, so a step-level
|
||||
# override is silently ignored. Pass the PR head SHA under
|
||||
# a non-reserved name and read it from alchemy.run.ts.
|
||||
BUILD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
GITHUB_TOKEN: ${{ steps.bot-token.outputs.token }}
|
||||
|
||||
cleanup:
|
||||
runs-on: ubuntu-latest
|
||||
if:
|
||||
${{ github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
}}
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Generate bot token
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
- name: Safety Check
|
||||
run: |-
|
||||
if [ "${{ env.STAGE }}" = "prod" ]; then
|
||||
echo "ERROR: Cannot destroy prod environment in cleanup job"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Destroy Preview Environment
|
||||
working-directory: website
|
||||
run: bun alchemy destroy --stage ${{ env.STAGE }} --yes
|
||||
env:
|
||||
CLOUDFLARE_API_KEY: ${{ secrets.ADMIN_CLOUDFLARE_API_KEY }}
|
||||
CLOUDFLARE_EMAIL: ${{ secrets.ADMIN_CLOUDFLARE_EMAIL }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
|
||||
PULL_REQUEST: ${{ github.event.number }}
|
||||
GITHUB_TOKEN: ${{ steps.bot-token.outputs.token }}
|
||||
@@ -0,0 +1,180 @@
|
||||
name: pr-package
|
||||
|
||||
# Publishes alchemy + better-auth + pr-package tarballs to the pr-package
|
||||
# service at pkg.ing on every push to main and every PR sync. On PR close,
|
||||
# deletes every tag we ever assigned for that PR so the underlying tarballs
|
||||
# become orphaned and the bucket cleans them up.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, closed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
PR_PACKAGE_HOST: pkg.ing
|
||||
NODE_VERSION: "24"
|
||||
|
||||
jobs:
|
||||
# ── Publish on push-to-main and PR sync. ──────────────────────────────────
|
||||
publish:
|
||||
if: github.event_name == 'push' || (github.event_name == 'pull_request' &&
|
||||
github.event.action != 'closed')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
# Build everything: tsdown bundles alchemy (bin/ + cli lib) and tsc -b
|
||||
# populates lib/ for the layer packages (better-auth, pr-package).
|
||||
# Their tarballs ship both src/ and lib/, and consumers in non-bun
|
||||
# runtimes resolve via the `import` condition → ./lib/index.js.
|
||||
- run: bun run build:packages
|
||||
|
||||
- name: Compute tags
|
||||
id: tags
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
# `head_ref` for PRs (source branch), `ref_name` for push (e.g. "main").
|
||||
BRANCH: ${{ github.event_name == 'pull_request' && github.head_ref ||
|
||||
github.ref_name }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
# PR builds run on the merge commit by default; tag the actual head sha
|
||||
# so consumers can pin to a specific PR commit.
|
||||
SHA: ${{ github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.sha || github.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
short="${SHA:0:7}"
|
||||
long="$SHA"
|
||||
tags=("$short" "$long" "$BRANCH")
|
||||
if [ "$EVENT" = "pull_request" ]; then
|
||||
tags+=("pr-${PR_NUMBER}")
|
||||
fi
|
||||
json=$(printf '%s\n' "${tags[@]}" | jq -R . | jq -s -c .)
|
||||
echo "tags=$json" >> "$GITHUB_OUTPUT"
|
||||
echo "short=$short" >> "$GITHUB_OUTPUT"
|
||||
echo "Tags: $json"
|
||||
|
||||
# PR builds expire after 1 week; pushes to main omit the header and
|
||||
# fall back to the worker's defaultTtl (3 weeks).
|
||||
- name: Publish alchemy
|
||||
env:
|
||||
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
TAGS: ${{ steps.tags.outputs.tags }}
|
||||
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
|
||||
working-directory: packages/alchemy
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f *.tgz
|
||||
bun pm pack --destination .
|
||||
tgz=$(ls *.tgz)
|
||||
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
|
||||
curl -fsSL --show-error -X PUT \
|
||||
"https://${PR_PACKAGE_HOST}/projects/alchemy/packages" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "X-Tags: ${TAGS}" \
|
||||
${TTL:+-H "X-TTL: ${TTL}"} \
|
||||
-H "Content-Type: application/gzip" \
|
||||
--data-binary "@${tgz}"
|
||||
|
||||
- name: Publish better-auth
|
||||
env:
|
||||
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
TAGS: ${{ steps.tags.outputs.tags }}
|
||||
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
|
||||
working-directory: packages/better-auth
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f *.tgz
|
||||
bun pm pack --destination .
|
||||
tgz=$(ls *.tgz)
|
||||
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
|
||||
curl -fsSL --show-error -X PUT \
|
||||
"https://${PR_PACKAGE_HOST}/projects/@alchemy.run/better-auth/packages" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "X-Tags: ${TAGS}" \
|
||||
${TTL:+-H "X-TTL: ${TTL}"} \
|
||||
-H "Content-Type: application/gzip" \
|
||||
--data-binary "@${tgz}"
|
||||
|
||||
- name: Publish pr-package
|
||||
env:
|
||||
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
TAGS: ${{ steps.tags.outputs.tags }}
|
||||
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
|
||||
working-directory: packages/pr-package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f *.tgz
|
||||
bun pm pack --destination .
|
||||
tgz=$(ls *.tgz)
|
||||
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
|
||||
curl -fsSL --show-error -X PUT \
|
||||
"https://${PR_PACKAGE_HOST}/projects/@alchemy.run/pr-package/packages" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "X-Tags: ${TAGS}" \
|
||||
${TTL:+-H "X-TTL: ${TTL}"} \
|
||||
-H "Content-Type: application/gzip" \
|
||||
--data-binary "@${tgz}"
|
||||
|
||||
# PR-only: leave a sticky comment with the install URLs pinned to this
|
||||
# commit. Uses pkg.ing (the canonical short host), which serves both
|
||||
# the pretty alias paths and the underlying /projects/:project/tags/:tag
|
||||
# API directly.
|
||||
- name: Generate bot token
|
||||
if: github.event_name == 'pull_request'
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- name: Comment on PR
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.bot-token.outputs.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
SHORT_SHA: ${{ steps.tags.outputs.short }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
MARKER="<!-- pr-package-comment -->"
|
||||
# Use `bun add <name>@<url>` instead of `bun add <url>`. Without an
|
||||
# explicit name, bun's resolver hits a DependencyLoop bug when the
|
||||
# consumer already has the same package name resolved from npm
|
||||
# (oven-sh/bun#5789, oven-sh/bun#17946). The aliased form bypasses
|
||||
# the buggy reconciliation path and works on fresh and existing
|
||||
# projects alike.
|
||||
BODY=$(printf '%s\n\nInstall the packages built from this commit:\n\n**alchemy**\n```sh\nbun add alchemy@https://pkg.ing/alchemy/%s\n```\n\n**@alchemy.run/better-auth**\n```sh\nbun add @alchemy.run/better-auth@https://pkg.ing/@alchemy.run/better-auth/%s\n```\n\n**@alchemy.run/pr-package**\n```sh\nbun add @alchemy.run/pr-package@https://pkg.ing/@alchemy.run/pr-package/%s\n```\n' "$MARKER" "$SHORT_SHA" "$SHORT_SHA" "$SHORT_SHA")
|
||||
|
||||
existing=$(gh api --paginate \
|
||||
"repos/${REPO}/issues/${PR_NUMBER}/comments" \
|
||||
--jq ".[] | select(.user.login == \"alchemy-version-bot[bot]\") | select(.body | startswith(\"${MARKER}\")) | .id" \
|
||||
| head -1)
|
||||
|
||||
if [ -n "$existing" ]; then
|
||||
gh api -X PATCH "repos/${REPO}/issues/comments/${existing}" -f body="$BODY"
|
||||
else
|
||||
gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -f body="$BODY"
|
||||
fi
|
||||
+432
@@ -0,0 +1,432 @@
|
||||
name: Release NPM Package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Release channel"
|
||||
required: true
|
||||
type: choice
|
||||
default: beta
|
||||
options:
|
||||
- release
|
||||
- beta
|
||||
- alpha
|
||||
- tag
|
||||
spec:
|
||||
description: >-
|
||||
Channel-specific value. tag: REQUIRED, the explicit full version (e.g.
|
||||
2.0.0-experimental.1). release: REQUIRED, patch|minor|major or an
|
||||
explicit x.y.z. beta|alpha: optional, an integer N to force
|
||||
2.0.0-<channel>.N; leave blank to auto-increment.
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
NODE_VERSION: "24"
|
||||
# Files produced by the bump job and consumed by every publish job + the
|
||||
# final commit job. Listed once here so additions stay in sync.
|
||||
BUMP_ARTIFACT_PATHS: |
|
||||
packages/alchemy/lib
|
||||
packages/alchemy/bin
|
||||
packages/alchemy/package.json
|
||||
packages/better-auth/package.json
|
||||
packages/better-auth/lib
|
||||
packages/pr-package/package.json
|
||||
packages/pr-package/lib
|
||||
bun.lock
|
||||
jobs:
|
||||
# ── Step 1: Compute the next version and stage the bump in-memory. ──
|
||||
# No git commit: we want a failed publish to leave no orphan commit
|
||||
# behind. The staged files ride to the publish jobs (and the final commit
|
||||
# job) as an artifact.
|
||||
bump:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.bump.outputs.version }}
|
||||
channel: ${{ inputs.channel }}
|
||||
sha: ${{ steps.sha.outputs.sha }}
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
env:
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
SPEC: ${{ inputs.spec }}
|
||||
run: |
|
||||
case "$CHANNEL" in
|
||||
tag)
|
||||
if [ -z "$SPEC" ]; then
|
||||
echo "::error::'tag' channel requires an explicit version in 'spec' (e.g. 2.0.0-experimental.1)"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
release)
|
||||
if [ -z "$SPEC" ]; then
|
||||
echo "::error::'release' channel requires a 'spec' (patch|minor|major|x.y.z)"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- id: sha
|
||||
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- id: bump
|
||||
env:
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
SPEC: ${{ inputs.spec }}
|
||||
run: |
|
||||
if [ -n "$SPEC" ]; then
|
||||
VERSION=$(bun ./scripts/release/bump.ts "$CHANNEL" "$SPEC")
|
||||
else
|
||||
VERSION=$(bun ./scripts/release/bump.ts "$CHANNEL")
|
||||
fi
|
||||
echo "Resolved version: $VERSION (channel: $CHANNEL)"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Build everything once, up front, against the bumped versions. Outputs
|
||||
# ride to every publish job as the `build-output` artifact so we don't
|
||||
# rebuild three times in parallel.
|
||||
- run: bun run build:packages
|
||||
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
path: ${{ env.BUMP_ARTIFACT_PATHS }}
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: build-output
|
||||
path: |
|
||||
packages/*/lib
|
||||
packages/*/bin
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
include-hidden-files: true
|
||||
|
||||
# ── Step 2: Commit (bump + changelog) and tag BEFORE publishing.
|
||||
# Committing first means the publishable source of truth is the tagged
|
||||
# commit; publish jobs check it out by SHA. Durability: if a previous
|
||||
# attempt already committed and tagged but failed during npm publish, the
|
||||
# bump job's HEAD-tag detection reuses the existing version, and this job
|
||||
# detects HEAD is already at the tag and skips the commit/push.
|
||||
# Skipped for `tag` channel — those releases are intentionally uncommitted.
|
||||
commit-and-tag:
|
||||
needs: bump
|
||||
if: inputs.channel != 'tag'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
sha: ${{ steps.commit.outputs.sha }}
|
||||
steps:
|
||||
- name: Generate bot token
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.bot-token.outputs.token }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- name: Configure git
|
||||
run: |
|
||||
git config user.email "alchemy-version-bot[bot]@users.noreply.github.com"
|
||||
git config user.name "alchemy-version-bot[bot]"
|
||||
|
||||
- id: commit
|
||||
name: Commit bump + changelog, tag, push
|
||||
env:
|
||||
VERSION: ${{ needs.bump.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="v${VERSION}"
|
||||
|
||||
# Durability: if HEAD already points at the release tag (resumed
|
||||
# run after a previous attempt committed+tagged but publish
|
||||
# failed), there is nothing to do. Use HEAD as the publish SHA.
|
||||
HEAD_TAG=$(git describe --exact-match --tags HEAD 2>/dev/null || true)
|
||||
if [ "$HEAD_TAG" = "$TAG" ]; then
|
||||
echo "HEAD is already at ${TAG}; skipping commit/tag/push"
|
||||
SHA=$(git rev-parse HEAD)
|
||||
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Generate release notes; release-notes.ts is idempotent and
|
||||
# bails out if the tag heading is already present in CHANGELOG.md.
|
||||
bun scripts/release/release-notes.ts "${TAG}"
|
||||
|
||||
# Stage bump files (overwritten by the downloaded artifact) and
|
||||
# the new changelog entry as a single commit.
|
||||
git add packages/alchemy/package.json \
|
||||
packages/better-auth/package.json \
|
||||
packages/pr-package/package.json \
|
||||
bun.lock \
|
||||
CHANGELOG.md
|
||||
|
||||
if git diff --cached --quiet; then
|
||||
echo "No changes to commit (already on a release commit?)"
|
||||
else
|
||||
git commit -m "chore(release): ${VERSION}"
|
||||
fi
|
||||
|
||||
if ! git rev-parse --verify "refs/tags/${TAG}" >/dev/null 2>&1; then
|
||||
git tag -a "${TAG}" -m "Release ${TAG}"
|
||||
fi
|
||||
|
||||
git push origin HEAD
|
||||
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
|
||||
echo "Tag ${TAG} already on remote, skipping tag push"
|
||||
else
|
||||
git push origin "refs/tags/${TAG}"
|
||||
fi
|
||||
|
||||
SHA=$(git rev-parse HEAD)
|
||||
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# ── Step 3a: Build and publish `alchemy`. ──
|
||||
# For non-tag channels, checkout the just-committed tagged SHA; for the
|
||||
# `tag` channel (no commit), checkout the bump's pre-bump SHA and rely
|
||||
# on the bump-files artifact instead.
|
||||
publish-alchemy:
|
||||
needs: [bump, commit-and-tag]
|
||||
if:
|
||||
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
|
||||
== 'success' || needs.commit-and-tag.result == 'skipped')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Upgrade npm for OIDC trusted publishing
|
||||
run: |
|
||||
npm install -g npm@latest && npm --version
|
||||
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: build-output
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- run: bun scripts/release/publish-package.ts packages/alchemy ${{
|
||||
needs.bump.outputs.channel }}
|
||||
|
||||
# ── Step 3b: Build and publish `@alchemy.run/better-auth`. ──
|
||||
publish-better-auth:
|
||||
needs: [bump, commit-and-tag, publish-alchemy]
|
||||
if:
|
||||
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
|
||||
== 'success' || needs.commit-and-tag.result == 'skipped') &&
|
||||
needs.publish-alchemy.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Upgrade npm for OIDC trusted publishing
|
||||
run: |
|
||||
npm install -g npm@latest && npm --version
|
||||
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: build-output
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- run: bun scripts/release/publish-package.ts packages/better-auth ${{
|
||||
needs.bump.outputs.channel }}
|
||||
|
||||
# ── Step 3c: Build and publish `@alchemy.run/pr-package`. ──
|
||||
publish-pr-package:
|
||||
needs: [bump, commit-and-tag, publish-alchemy]
|
||||
if:
|
||||
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
|
||||
== 'success' || needs.commit-and-tag.result == 'skipped') &&
|
||||
needs.publish-alchemy.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Upgrade npm for OIDC trusted publishing
|
||||
run: |
|
||||
npm install -g npm@latest && npm --version
|
||||
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: build-output
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- run: bun scripts/release/publish-package.ts packages/pr-package ${{
|
||||
needs.bump.outputs.channel }}
|
||||
|
||||
# ── Step 4: Create GitHub Release and notify Discord. ──
|
||||
# Runs only after every publish job succeeded. The bump+changelog commit
|
||||
# and tag were already pushed by `commit-and-tag` before publishing.
|
||||
finalize:
|
||||
needs:
|
||||
[
|
||||
bump,
|
||||
commit-and-tag,
|
||||
publish-alchemy,
|
||||
publish-better-auth,
|
||||
publish-pr-package,
|
||||
]
|
||||
if: inputs.channel != 'tag'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha }}
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- name: Create GitHub Release
|
||||
env:
|
||||
VERSION: ${{ needs.bump.outputs.version }}
|
||||
CHANNEL: ${{ needs.bump.outputs.channel }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: bun scripts/release/github-release.ts "v${VERSION}" "${CHANNEL}"
|
||||
|
||||
- name: Notify Discord
|
||||
if: success() && env.DISCORD_WEBHOOK != ''
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
VERSION: ${{ needs.bump.outputs.version }}
|
||||
CHANNEL: ${{ needs.bump.outputs.channel }}
|
||||
run: bun scripts/release/discord-notify.ts "v${VERSION}" "${CHANNEL}"
|
||||
@@ -0,0 +1,93 @@
|
||||
name: test
|
||||
|
||||
# Smoke-tests `alchemy destroy → deploy → destroy` against each example.
|
||||
# `bun test:canary` drives the whole suite — it iterates both bun and pnpm
|
||||
# runtimes itself and publishes canary tarballs to pkg.ing before deploying.
|
||||
|
||||
on:
|
||||
# TODO(sam): re-enable these when they are running reliably and not polluting our account
|
||||
# push:
|
||||
# branches: [main]
|
||||
# pull_request:
|
||||
# types: [opened, reopened, synchronize]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
# Required for aws-actions/configure-aws-credentials to mint a session
|
||||
# via OIDC instead of long-lived AWS_ACCESS_KEY_ID secrets.
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
PKGING_HOST: pkg.ing
|
||||
NODE_VERSION: "24"
|
||||
# PR runs use `pr-<n>` so each PR has its own isolated cloud namespace;
|
||||
# main pushes use `main`; manual `workflow_dispatch` runs use the branch
|
||||
# name. Forwarded to the smoke test as $SMOKE_STAGE.
|
||||
SMOKE_STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}',
|
||||
github.event.number) || (github.ref == 'refs/heads/main' && 'main' ||
|
||||
github.ref_name) }}
|
||||
|
||||
concurrency:
|
||||
# Cancel an in-progress run for the same PR (or branch) when a new push
|
||||
# arrives — the smoke suite mutates real cloud state, so two parallel
|
||||
# runs against the same SMOKE_STAGE would race.
|
||||
group: test-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
smoke:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: bun-${{ runner.os }}-
|
||||
|
||||
# Bootstrap install so `bun test:canary` itself can resolve. The
|
||||
# test then runs its own `bun install` + `pnpm install` in canary
|
||||
# `beforeAll` after rewriting the catalog to pkg.ing tarballs, so
|
||||
# there's nothing pnpm-specific to wire up here.
|
||||
- run: bun install
|
||||
|
||||
# OIDC → short-lived AWS session. Exports AWS_ACCESS_KEY_ID,
|
||||
# AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION; the
|
||||
# `output-credentials: true` flag also surfaces aws-account-id as a
|
||||
# step output (which we forward as `AWS_ACCOUNT_ID` below — the
|
||||
# action does NOT set it as an env var on its own).
|
||||
- id: aws-creds
|
||||
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6.1.1
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE_ARN }}
|
||||
aws-region: ${{ vars.AWS_REGION }}
|
||||
output-credentials: true
|
||||
|
||||
- name: Smoke
|
||||
env:
|
||||
# AWS — `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
|
||||
# `AWS_SESSION_TOKEN`, `AWS_REGION` are already exported by
|
||||
# configure-aws-credentials; we only need to forward the account
|
||||
# id, which Alchemy's `loadFromEnv` requires when CI=true.
|
||||
AWS_ACCOUNT_ID: ${{ steps.aws-creds.outputs.aws-account-id }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.TEST_CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
|
||||
NEON_API_KEY: ${{ secrets.NEON_API_KEY }}
|
||||
PR_PACKAGE_TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
PKGING_HOST: ${{ env.PKGING_HOST }}
|
||||
SMOKE_STAGE: ${{ env.SMOKE_STAGE }}
|
||||
run: bun test:canary
|
||||
@@ -0,0 +1,48 @@
|
||||
node_modules/
|
||||
dist/
|
||||
/lib/
|
||||
/alchemy/lib/
|
||||
.out/
|
||||
.test/
|
||||
.DS_Store
|
||||
.env
|
||||
*.tsbuildinfo
|
||||
.claude/
|
||||
.alchemy/
|
||||
# !.alchemy/github:alchemy/
|
||||
# examples/*/.alchemy
|
||||
|
||||
.repomix-output.txt
|
||||
wrangler.jsonc
|
||||
|
||||
# Husky - ignore generated files but keep hooks
|
||||
.husky/_
|
||||
!.husky/pre-commit
|
||||
|
||||
.smoke
|
||||
.smoke.logs
|
||||
smoke
|
||||
# Generated by test/smoke.test.ts to make pnpm 11's deps-status check
|
||||
# resolve the bun catalog. Cleaned up at end of suite.
|
||||
pnpm-workspace.yaml
|
||||
.svelte-kit
|
||||
.astro
|
||||
.wrangler
|
||||
|
||||
*.tgz
|
||||
*.js
|
||||
*.d.ts
|
||||
*.map
|
||||
|
||||
.attest
|
||||
.cache
|
||||
.external
|
||||
.bundle-benchmark
|
||||
packages/alchemy/docs
|
||||
.sonda
|
||||
examples/cloudflare-worker/src/scratch.ts
|
||||
|
||||
!/packages/alchemy/bin/cli.js
|
||||
.vendor/*
|
||||
.tmp
|
||||
pnpm-lock.yaml
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "vendor/alchemy"]
|
||||
path = .vendor/alchemy
|
||||
url = [email protected]:alchemy-run/alchemy.git
|
||||
@@ -0,0 +1,2 @@
|
||||
bun format
|
||||
git update-index --again
|
||||
@@ -0,0 +1 @@
|
||||
# see: https://opencode.ai/docs/tools/#ignore-patterns
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"printWidth": 80,
|
||||
"endOfLine": "lf",
|
||||
"ternaries": true,
|
||||
"experimental_sort_imports": {
|
||||
"order": "asc"
|
||||
},
|
||||
"ignorePatterns": [
|
||||
"dist/**",
|
||||
"*.min.js",
|
||||
"**/lib/**",
|
||||
"**/mdx/**",
|
||||
"**/*.mdx",
|
||||
"**/*.md",
|
||||
"**/.vendor/**",
|
||||
"**/package.json"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"rules": {
|
||||
"no-misused-new": "off",
|
||||
"require-yield": "off",
|
||||
"no-non-null-asserted-optional-chain": "off"
|
||||
}
|
||||
}
|
||||
Submodule
+1
Submodule .repos/alchemy-effect/.vendor/alchemy added at c9f5e549cf.
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"diffEditor.renderSideBySide": false,
|
||||
"js/ts.experimental.useTsgo": true,
|
||||
"typescript.experimental.useTsgo": true,
|
||||
"typescript.tsdk": "node_modules/@typescript/native-preview/lib",
|
||||
"typescript.native-preview.tsdk": "node_modules/@typescript/native-preview/lib",
|
||||
"typescript.enablePromptUseWorkspaceTsdk": true,
|
||||
"typescript.preferences.importModuleSpecifier": "relative",
|
||||
"typescript.preferences.importModuleSpecifierEnding": "js",
|
||||
"oxc.enable": true,
|
||||
"oxc.lint.run": "onSave",
|
||||
"json.schemaDownload.enable": true,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.codeLens": false,
|
||||
"editor.formatOnSave": true,
|
||||
"editor.formatOnSaveMode": "file",
|
||||
"editor.inlayHints.enabled": "offUnlessPressed",
|
||||
"editor.tabSize": 2,
|
||||
"editor.indentSize": 2,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll": "explicit",
|
||||
"source.organizeImports": "explicit"
|
||||
},
|
||||
"[toml]": {
|
||||
"editor.defaultFormatter": "tamasfe.even-better-toml"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "vscode.json-language-features"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "vscode.json-language-features"
|
||||
},
|
||||
"[markdown]": {
|
||||
"editor.formatOnSave": false,
|
||||
"editor.defaultFormatter": null
|
||||
},
|
||||
"[mdx]": {
|
||||
"editor.defaultFormatter": null,
|
||||
"editor.formatOnSave": false
|
||||
},
|
||||
"files.exclude": {
|
||||
"**/__pycache__": true,
|
||||
"**/*.pyc": true,
|
||||
"packages/alchemy/bin/**/*.js*": true,
|
||||
"packages/alchemy/bin/**/*.d*": true
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[javascript]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[javascriptreact]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"oxc.enable.oxfmt": true
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
# alchemy
|
||||
|
||||
Alchemy Effect is an Infrastructure-as-Effects (IaE) framework that extends Infrastructure-as-Code (IaC) by combining business logic and infrastructure config into a single, type-safe program expressed as Effects.
|
||||
|
||||
It includes a core IaC engine built with Effect. Effect provides the foundation for type-safe, composable, and testable infrastructure programs. It brings errors into the type-system and provides declarative/composable retry logic that ensure proper and reliable handling of failures.
|
||||
|
||||
# Concepts
|
||||
|
||||
- **Cloud Provider** - a cloud provider that offers a set of Services, e.g. AWS, Azure, GCP, Cloudflare, Stripe, Planetscale, Neon, etc.
|
||||
- **Service** - a collection of Resources, Functions, and Bindings offered by a Cloud Provider.
|
||||
- **Resource** - a named entity that is configuted with "Input Properties" and produces "Output Attributes". May or may not have Binding Contract.
|
||||
- **Input Properties** - the properties passed as input to configure a Resource. Otherwise known as the "desired state" of the Resource.
|
||||
- **Output Attributes** - the attributes produced by a Resource. Otherwise known as the "current state" of the Resource.
|
||||
- **Stable Properties** - properties that are not affected by an Update, e.g. the ID or ARN of a Resource.
|
||||
- **Function** (aka. **Runtime**) - a special kind of Resource that includes a runtime implementation expressed as a Function producing an `Effect<A, Err, Req>`. The `Req` type captures runtime dependencies, from which Infrastructure Dependencies are inferred.
|
||||
- **Resource Provider** (see [Provider](./packages/alchemy/src/Provider.ts))
|
||||
|
||||
A Resource Provider implements the following Lifecycle Operations:
|
||||
|
||||
- **Diff** - compares new props with old props and determines if the Resource needs to be updated or replaced. For updates, it can also specify a list of Stable Properties that will not be changed by the update.
|
||||
- **Read** - reads the current state of a Resource and returns the current Output Attributes. May return `Unowned(attrs)` to signal an existing-but-foreign resource that the engine should refuse to take over unless `--adopt` is set.
|
||||
- **Pre-Create** - an optional operation that creates a stub of a Resource before reconcile runs. Used to resolve circular dependencies — e.g. Function A and B depend on each other, so we create a stub of Function A first and then `reconcile` later wires up the real dependency.
|
||||
- **Reconcile** - converges a Resource's actual cloud state to the desired state described by the new Input Properties. Called for both first-time provisioning and subsequent updates. The provider receives `output` (current Attributes) and `olds` (previous Props) which may both be `undefined` on a greenfield create, both defined on an update, or `output !== undefined && olds === undefined` on an adoption. See the **Reconciler doctrine** section below for the required shape.
|
||||
- **Delete** - deletes an existing Resource. It must be designed as idempotent because it is always possible for state persistence to fail after the delete operation is called. If the resource doesn't exist during deletion, it should not be considered an error.
|
||||
- **Capability** - a runtime requirement of a Function (e.g. require `SQS.SendMessage` on a `SQS.Queue`). Each Capability is split into two parts: a `Binding.Service` (runtime SDK wrapper) and a `Binding.Policy` (deploy-time IAM/binding attachment).
|
||||
- **Binding.Service** - an Effect Service that wraps an SDK client and exposes a `.bind(resource)` method returning a typed callable for runtime use. Provided as a Layer on the **Function** Effect so it gets bundled into the Lambda/Worker. See [Binding](./packages/alchemy/src/Binding.ts).
|
||||
- **Binding.Policy** - an Effect Service that runs only at deploy time to attach IAM policies (AWS) or bindings (Cloudflare) to a Function's role/config. At runtime, `Binding.Policy` uses `Effect.serviceOption` so it gracefully becomes a no-op when the layer is not provided. Policy layers are provided on the **Stack** via `AWS.providers()()`, not on the Function.
|
||||
- **Binding** - data attached to a Resource via `resource.bind(data)`. A Binding is a `{ context: PolicyContext, data: BindingData }` tuple that is collected on the Stack during plan/deploy. Bindings enable circular references between Resources — the `Binding.Policy` calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records the binding data on the Stack. The Resource Provider then receives the resolved binding data in its `reconcile` lifecycle operation via the `bindings` parameter.
|
||||
- **Binding Contract** - the shape of data a Resource accepts from Bindings. For example, a Lambda Function accepts `{ env?: Record<string, any>, policyStatements?: PolicyStatement[] }` because it needs environment variables and IAM policies. A Cloudflare Worker accepts `{ bindings: Worker.Binding[] }` for its native binding system. The Binding Contract is declared as the fourth type parameter on the `Resource` interface. See [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) and [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts).
|
||||
- **Dependency** - Resources depend on other Resources through two mechanisms:
|
||||
- Output Properties of one Resource passed as Input Properties to another Resource (non-circular, directed acyclic graph)
|
||||
- Bindings that attach data (IAM policies, env vars, Cloudflare bindings) from one Resource to another, enabling circular references between Resources.
|
||||
- **Output** - a reference to (or derived from) a Resource's "Output Attributes". E.g. Bucket.bucketArn
|
||||
- **Stack** - a collection of Resources, Functions, and Bindings that are deployed together.
|
||||
- **Stack Name** - the name of a Stack, e.g. `my-stack`
|
||||
- **Stage** - the stage of a Stack, e.g. `dev`, `prod`, `dev-sam`
|
||||
- **Stack Instance** - a deployed instance of a Stack+Stage
|
||||
- **Resource Type** - the type of a Resource, e.g. `Bucket`, `Instance`
|
||||
- **Physical Name** - a unique name for a Resource, e.g. `my-bucket-1234567890`. It is usually best to generate them using the built-in createPhysicalName utility function which generates
|
||||
- **Logical ID** - the logical ID identifying a resource within a Stack, e.g. `my-bucket`. It is stable across creates, updates, deletes and replaces.
|
||||
- **Instance ID** - a unique identifier for an instance of a Resource. It is stable across creates, updates and deletes. It changes when a resource is replaced. It is truncated and used as the suffix of the Physical Name.
|
||||
- **Event Source** - a special kind of Binding between a Function and a Resource that produces events that invoke the Function, e.g. `SQS.QueueEventSource`. Event Sources are implemented as Binding.Service + Binding.Policy pairs, where the attach logic creates/updates the event source mapping via the cloud provider API.
|
||||
- **Replacement** - the process of replacing a Resource with a new one. A new one is created, downstream dependencies are updated with the new reference, and then the old one is deleted. Or, the old one is deleted first and then the new one is created.
|
||||
- **Dependency Violation** - an error that some APIs call when an operation cannot be performed because a dependency is not met. E.g. you cannot delete an EIP until the NAT Gateway it is attached to is deleted. Lifecycle operations typically retry Dependency Violations.
|
||||
- **Eventual Consistency** - create/update/delete operations can be eventually consistent leading to a variety of failure modes. For example, a Resource may be created but not yet available for use, or a Resource may be deleted but still appear in the console. Errors caused by eventual consistency should be retried, and lifecycle operations/tests should be carefully designed to wait for consistency before proceeding.
|
||||
- **Retryable Error** - an error that can be retried. E.g. a Dependency Violation, Eventual Consistency Error, Transient Failure, etc.
|
||||
- **Non-Retryable Error** - an error that cannot be retried. E.g. a Validation Error, Authorization Error, etc.
|
||||
- **Retry Policy** - a policy for retrying errors. E.g. a fixed delay, exponential backoff, max retries, while some condition is true, or until some condition is true/false, etc.
|
||||
|
||||
# File System Conventions
|
||||
|
||||
Each Service's Resources follow the same pattern. Resource contract and provider are co-located in the same file. Capabilities (Binding.Service + Binding.Policy) are in separate files named after the capability.
|
||||
|
||||
```sh
|
||||
# source files
|
||||
packages/alchemy/src/{Cloud}/{Service}/index.ts # re-exports all resources and capabilities
|
||||
packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts # resource contract + resource provider
|
||||
packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts # Binding.Service + Binding.Policy for a capability
|
||||
# test files
|
||||
packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts
|
||||
# docs (auto-generated from source-code JSDoc - DO NOT manually edit)
|
||||
website/src/content/docs/providers/{Cloud}/{Resource}.md # API reference, generated by `bun generate:api-reference`
|
||||
```
|
||||
|
||||
Examples of actual paths:
|
||||
|
||||
```sh
|
||||
packages/alchemy/src/AWS/S3/Bucket.ts # S3 Bucket resource + provider
|
||||
packages/alchemy/src/AWS/S3/GetObject.ts # S3 GetObject Binding.Service + Binding.Policy
|
||||
packages/alchemy/src/AWS/S3/PutObject.ts # S3 PutObject Binding.Service + Binding.Policy
|
||||
packages/alchemy/src/AWS/SQS/Queue.ts # SQS Queue resource + provider
|
||||
packages/alchemy/src/AWS/SQS/SendMessage.ts # SQS SendMessage capability
|
||||
packages/alchemy/src/AWS/Kinesis/Stream.ts # Kinesis Stream resource + provider
|
||||
packages/alchemy/src/AWS/Kinesis/PutRecord.ts # Kinesis PutRecord capability
|
||||
packages/alchemy/src/AWS/Lambda/Function.ts # Lambda Function resource + provider
|
||||
packages/alchemy/src/AWS/DynamoDB/Table.ts # DynamoDB Table resource + provider
|
||||
packages/alchemy/src/AWS/DynamoDB/GetItem.ts # DynamoDB GetItem capability
|
||||
packages/alchemy/src/AWS/EC2/Vpc.ts # VPC resource + provider
|
||||
packages/alchemy/src/AWS/EC2/Subnet.ts # Subnet resource + provider
|
||||
```
|
||||
|
||||
# Documentation Generation
|
||||
|
||||
**Source of truth:** The source code is the single source of truth for all API documentation. JSDoc comments in `packages/alchemy/src/**/*.ts` are extracted and used to generate the public API reference markdown.
|
||||
|
||||
:::warning
|
||||
**Never edit the generated markdown files** under `website/src/content/docs/providers/{Cloud}/`. They are overwritten on every regeneration.
|
||||
|
||||
To "update the docs", edit the JSDoc on the source `.ts` file (resource-level JSDoc on the exported `const`, plus field-level JSDoc on each prop/attribute) and re-run the generator. There is no separate doc file to update.
|
||||
:::
|
||||
|
||||
**How to generate docs:**
|
||||
|
||||
```sh
|
||||
bun generate:api-reference # -> website/src/content/docs/providers/{Cloud}/{Resource}.md
|
||||
```
|
||||
|
||||
This is the only doc generator that produces user-facing output. ([scripts/generate-api-reference.ts](./scripts/generate-api-reference.ts)) does the following:
|
||||
|
||||
1. Discovers resource files in `packages/alchemy/src/{Cloud}/{Service}/`
|
||||
2. Parses TypeScript with `ts-morph`
|
||||
3. Extracts the resource-level summary plus `@section` / `@example` blocks from JSDoc
|
||||
4. Writes one markdown file per resource at `website/src/content/docs/providers/{Cloud}/{Resource}.md`
|
||||
|
||||
After editing JSDoc on a resource, run `bun generate:api-reference` to refresh the website docs.
|
||||
|
||||
**Writing good documentation:** When adding or updating a resource, ensure all Props and Attrs have JSDoc comments:
|
||||
|
||||
```typescript
|
||||
export interface BucketProps {
|
||||
/**
|
||||
* Name of the bucket. If omitted, a unique name will be generated.
|
||||
* Must be lowercase and between 3-63 characters.
|
||||
*/
|
||||
bucketName?: string;
|
||||
|
||||
/**
|
||||
* Whether to delete all objects when the bucket is destroyed.
|
||||
* @default false
|
||||
*/
|
||||
forceDestroy?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
The `@default` tag is used to document default values and will appear in the generated documentation.
|
||||
|
||||
### Examples and Sections (IMPORTANT)
|
||||
|
||||
**Examples are critical for documentation.** Every resource should have examples demonstrating common use cases. Use `@section` and `@example` JSDoc tags on the main Resource export to organize examples into a navigable table of contents.
|
||||
|
||||
**Format:**
|
||||
|
||||
- `@section <Section Title>` - Creates a heading in the Examples section and adds an entry to the Quick Reference table of contents
|
||||
- `@example <Example Title>` - Creates a subheading for a specific code example (must follow a `@section`)
|
||||
- Code blocks inside examples use standard markdown fenced code blocks (` `)
|
||||
|
||||
**Example:**
|
||||
|
||||
````typescript
|
||||
/**
|
||||
* An S3 bucket for storing objects.
|
||||
*
|
||||
* @section Creating a Bucket
|
||||
* @example Basic Bucket
|
||||
* ```typescript
|
||||
* const bucket = yield* Bucket("my-bucket", {});
|
||||
* ```
|
||||
*
|
||||
* @example Bucket with Force Destroy
|
||||
* ```typescript
|
||||
* const bucket = yield* Bucket("my-bucket", {
|
||||
* forceDestroy: true,
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @section Reading Objects
|
||||
* @example Get Object from Bucket
|
||||
* ```typescript
|
||||
* const response = yield* getObject(bucket, { key: "my-key" });
|
||||
* const body = yield* Effect.tryPromise(() => response.Body?.transformToString());
|
||||
* ```
|
||||
*
|
||||
* @section Writing Objects
|
||||
* @example Put Object to Bucket
|
||||
* ```typescript
|
||||
* yield* putObject(bucket, {
|
||||
* key: "hello.txt",
|
||||
* body: "Hello, World!",
|
||||
* contentType: "text/plain",
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export const Bucket = Resource<...>("AWS.S3.Bucket");
|
||||
````
|
||||
|
||||
This generates:
|
||||
|
||||
1. A "Quick Reference" section with links to each `@section`
|
||||
2. An "Examples" section with organized code examples under each section heading
|
||||
|
||||
**Best practices for examples:**
|
||||
|
||||
- Start with the simplest use case and progress to more complex ones
|
||||
- Include examples for all major capabilities (GetObject, PutObject, etc.)
|
||||
- Show real-world patterns like error handling, combining with other resources
|
||||
- Use descriptive titles that explain what the example demonstrates
|
||||
|
||||
# Workflow
|
||||
|
||||
Development of Alchemy-Effect Resources is heavily pattern based. Each Service has many Resources that each have 0 oor more Capabilities and Event Sources. When working on a new Service, the following steps should be followed.
|
||||
|
||||
1. Research the AWS Service and identify its Resources, Identifier Types, Structs, Capabilities, and Event Sources. Refer to the corresponding Terraform Provider, Pulumi Provider, and CloudFormation docs for that service (use the provided tools specifically for searching these docs for services and resources).
|
||||
|
||||
Example (abbreviated):
|
||||
|
||||
Service: S3
|
||||
|
||||
Resources:
|
||||
|
||||
- Bucket
|
||||
- BucketPolicy
|
||||
- etc.
|
||||
|
||||
Bucket Capabilities:
|
||||
|
||||
- GetObject
|
||||
- PutObject
|
||||
- DeleteObject
|
||||
|
||||
Identifier Types:
|
||||
|
||||
- Bucket Name
|
||||
- Bucket ARN
|
||||
|
||||
Structs:
|
||||
|
||||
- CorsRule
|
||||
- LifecycleConfiguration
|
||||
|
||||
2. Document each of the Resource interfaces
|
||||
|
||||
Include the following information:
|
||||
|
||||
- ResourceName, e.g. Bucket, Instance, Queue
|
||||
- Input Properties (for each property: Name, Type, Description, Default Value, Required, Constraints, Replaces: true/false)
|
||||
- Output Attributes (for each attribute: Name, Type, Description)
|
||||
|
||||
3. Document each of the Capabilities and Bindings
|
||||
|
||||
Include the following information:
|
||||
|
||||
- Capability Name, e.g. `GetObject`, `PutObject` (it maps 1:1 with an AWS API)
|
||||
- Constraints (e.g. `Key`)
|
||||
- IAM Policies (how the capability maps to an IAM Policy, e.g. Effect: Allow, Action: s3:GetObject, Resource: `arn:aws:s3:::${bucketName}/${Key}`)
|
||||
- Environment Variables (what environment variables should be added to a Lambda Function so that it can access the capability, e.g. `BUCKET_NAME`, `BUCKET_ARN`, `QUEUE_URL`, `QUEUE_ARN`, etc.)
|
||||
|
||||
4. Research and design each of the Lifecycle Operations
|
||||
|
||||
- **Diff** - identify which properties are always stable across any update, which properties change conditionally depending on new and old values, which properties trigger a replacement. This is usually just a distinct list, but can sometimes require if-this-then-that logic. Document it explicitly and exhaustively. Cross-reference with AWS CloudFormation, Terraform Provider and Pulumi Provider docs.
|
||||
|
||||
:::warning
|
||||
You should almost never use `no-op` in the Diff. No-op should be explicitly designed as a way to say "i know this property changed, but i don't want it to trigger an update". This is an edge-case and not the norm. Usually you want diff to return `undefined` or `void` to let the engine apply the default update logic. Diff is usually just use as an optimization or to identify replacement instead of update.
|
||||
:::
|
||||
|
||||
- **Read** - determine which API calls are required to read the Output Attributes of a Resource from the Cloud Provider state (otherwise known as refresh or synchronize resource state). This is usually a single Get{Resource} API call, but can be a complex set of calls depending on the Service. Read can also be called without the current Output Attributes because of past state persistence failures. These cases are handled by computing the deterministic Physical Name and looking it up or by searching for Resources using tags (if the Cloud Provider supports it). Read may return `Unowned(attrs)` when the resource exists but lacks our ownership tags, signalling the engine to gate adoption behind `--adopt` or `adopt(true)`.
|
||||
- **Pre-Create** - determine if the Resource needs a pre-create operation. This is usually only the case for the special Function/Runtime Resources like AWS Lambda Functions. If it is required, then document which API call(s) should be called and what the empty (unit) input properties are. E.g. a Lambda Function takes a simple script that exports a no-op handler function.
|
||||
- **Reconcile** - determine the API calls needed to converge the cloud's actual state to the desired state described by the new Input Properties. Reconcile must be a single flow that works whether the resource is missing (greenfield create), pre-existing under our ownership (update), or freshly adopted (`output` defined but `olds` absent). See the **Reconciler doctrine** section below.
|
||||
- **Delete** - determine which APIs should be called and in what order to delete an existing Resource. Delete should be idempotent so that if the resource has already been deleted, it is not considered an error. It is common for deletions to fail because of Dependency Violations or Eventual Consistency Errors. These are not always called Dependency Violations in the API docs, so attention should be paid to investigating each API's possible error codes and how they should be handled by the Delete operation. Should we retry for a period of time, indefinitely, or fail immediately?
|
||||
|
||||
# Reconciler doctrine
|
||||
|
||||
The provider's `reconcile` function replaces the legacy `create` + `update` pair. It runs every time the engine wants to make the cloud match the desired state — whether that's the first time the resource is being provisioned, a routine update, or a takeover after `read` returned an existing cloud resource.
|
||||
|
||||
It receives `output: Attributes | undefined` and `olds: Props | undefined`:
|
||||
|
||||
| `output` | `olds` | Meaning |
|
||||
| ------------ | ------------ | ------------------------------------------------- |
|
||||
| `undefined` | `undefined` | Greenfield — no prior physical resource |
|
||||
| defined | defined | Routine update — engine-owned resource |
|
||||
| defined | `undefined` | Adoption — engine adopted via `read` |
|
||||
|
||||
A reconciler MUST work correctly for all three combinations. It MUST NOT branch the body on `output === undefined` and run different code paths for "create" vs "update". That pattern is just rename-and-branch and re-introduces every assumption the old `create`/`update` split made. Instead, write one flow:
|
||||
|
||||
```
|
||||
1. Observe — derive the physical identifier; read live cloud state via getX/describeX
|
||||
2. Ensure — if the resource is missing, call createX. Catch AlreadyExists/ConflictException
|
||||
as a race and continue. Wait for active state if applicable.
|
||||
3. Sync — for each mutable aspect (settings, sub-resources, tags, policy):
|
||||
- read OBSERVED cloud state (not olds)
|
||||
- compute desired state from news + bindings
|
||||
- diff observed against desired
|
||||
- apply only the delta API call (skip the API entirely on no-op)
|
||||
4. Return — re-read final state if needed; return the fresh Attributes shape
|
||||
```
|
||||
|
||||
Key invariants:
|
||||
|
||||
- **Observation > assumption.** Cloud state is authoritative. `olds` is at most a hint to skip a no-op API call; it is never the source of truth for what's actually deployed.
|
||||
- **Each sync step is independently idempotent.** Crash mid-reconcile, re-run, you converge.
|
||||
- **`output` is treated as a cache** for stable identifiers (physical name, ARN, immutable id). It is NOT a guarantee that the resource still exists. If it doesn't, observation falls through to "missing" and ensure recreates.
|
||||
- **`AlreadyExists`/`NotFoundException`/`ResourceInUseException`-style errors are caught**, not propagated — they're races or eventual-consistency, not failures.
|
||||
- **Tags use observed cloud tags as the diff baseline**, not `olds.tags` or `output.tags`. Adoption may bring you a resource with foreign tags that need to be reconciled.
|
||||
|
||||
:::warning
|
||||
**Do not write `if (output === undefined) { /* create body */ } else { /* update body */ }`.** That is rename-and-branch, not reconciliation. The reconciler's body is one observe-ensure-sync flow that produces correct cloud state regardless of starting point.
|
||||
:::
|
||||
|
||||
The canonical reference reconcilers cover the common shapes:
|
||||
|
||||
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts) — uses `ensureBucketExists` + `syncBucketTags` + `syncBucketPolicy` helpers; each helper is itself a tiny reconciler.
|
||||
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts) — observe via `getQueueUrl`, ensure via `createQueue` (tolerates `QueueNameExists` race), sync attributes by diffing `getQueueAttributes` against desired, sync tags.
|
||||
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts) — many mutable aspects (mode, shards, retention, encryption, metrics), each its own observed-vs-desired sync block.
|
||||
- [DynamoDB Table](./packages/alchemy/src/AWS/DynamoDB/Table.ts) — multi-API observation (table + tags + PITR + TTL), per-aspect diffing, GSI delta application.
|
||||
- [EC2 Vpc](./packages/alchemy/src/AWS/EC2/Vpc.ts) — auto-assigned id, observe via `describeVpcs([output.vpcId])` with NotFound fallback to create, sync DNS attrs by reading `describeVpcAttribute`, sync tags from observed `vpc.Tags`.
|
||||
- [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) — uses `createOrUpdateFunction` / `createOrUpdateFunctionUrl` / `attachBindings` helpers, each idempotent.
|
||||
- [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts) — non-AWS API; the underlying `putWorker` is a true upsert, so reconcile observes existing settings and delegates.
|
||||
|
||||
Existence-only resources (Lambda Permission, EC2 Route, EC2 RouteTableAssociation, IAM AccessKey, etc.) have nothing mutable beyond their identity. Their reconciler is just observe → if missing, create. There is no sync step.
|
||||
|
||||
5. Research and design the test cases for each resource. Test cases can be single or multi-step. Single-step test cases are just testing a single create success or failure mode. Multi-step cases are testing a sequence of operations, starting with create and then updating or replacing the resource multiple times. Test cases should be designed to be exhaustive and cover all possible success and failure modes, starting from simple happy paths to long, complicated aggregate (including other resources) smoke tests.
|
||||
6. Implement the Resource contract and Provider in `packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts`.
|
||||
|
||||
The Resource contract (Props, Attributes, Binding Contract) and the Resource Provider (lifecycle operations) are co-located in the same file.
|
||||
|
||||
Read through the established examples to understand the pattern:
|
||||
|
||||
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts)
|
||||
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts)
|
||||
- [DynamoDB Table](./packages/alchemy/src/AWS/DynamoDB/Table.ts)
|
||||
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts)
|
||||
- [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts)
|
||||
- [VPC](./packages/alchemy/src/AWS/EC2/Vpc.ts)
|
||||
- [Subnet](./packages/alchemy/src/AWS/EC2/Subnet.ts)
|
||||
|
||||
The Resource interface takes four type parameters: `Resource<Type, Props, Attributes, BindingContract>`.
|
||||
|
||||
```ts
|
||||
export interface Stream extends Resource<
|
||||
"AWS.Kinesis.Stream",
|
||||
StreamProps,
|
||||
{
|
||||
streamName: string;
|
||||
streamArn: string;
|
||||
streamStatus: StreamStatus;
|
||||
}
|
||||
> {}
|
||||
|
||||
export const Stream = Resource<Stream>("AWS.Kinesis.Stream");
|
||||
```
|
||||
|
||||
For Resources that accept Bindings (like Lambda Function), include a fourth type parameter for the Binding Contract:
|
||||
|
||||
```ts
|
||||
export interface Function extends Resource<
|
||||
"AWS.Lambda.Function",
|
||||
FunctionProps,
|
||||
{
|
||||
functionArn: string;
|
||||
functionName: string;
|
||||
functionUrl: string | undefined;
|
||||
roleName: string;
|
||||
roleArn: string;
|
||||
},
|
||||
{
|
||||
env?: Record<string, any>;
|
||||
policyStatements?: PolicyStatement[];
|
||||
}
|
||||
> {}
|
||||
```
|
||||
|
||||
:::tip
|
||||
Some Input Property types are wrapped in an `Input<T>`, but not all are. Only properties that may need to be references to another resource's Output Attribute. E.g. common use-cases are `Input<VpcId>`, `Input<QueueUrl>`, `Tags: Record<string, Input<string>>`.
|
||||
:::
|
||||
|
||||
:::warning
|
||||
For fields like `name: string`, `bucketName: string`, `bucketPrefix: string`, you should not use `Input<string>` because these properties need to be statically knowable in the `diff` function.
|
||||
:::
|
||||
|
||||
7. Implement the Capabilities as `Binding.Service` + `Binding.Policy` pairs in `packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts`.
|
||||
|
||||
Each capability has two parts:
|
||||
|
||||
- **`Binding.Service`** — runtime SDK wrapper, provided on the Function Effect (bundled into Lambda/Worker)
|
||||
- **`Binding.Policy`** — deploy-time IAM policy attachment, provided on the Stack via `AWS.providers()()` (never bundled)
|
||||
|
||||
Read through the established capabilities to understand the pattern:
|
||||
|
||||
- [S3 GetObject](./packages/alchemy/src/AWS/S3/GetObject.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [S3 PutObject](./packages/alchemy/src/AWS/S3/PutObject.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [SQS SendMessage](./packages/alchemy/src/AWS/SQS/SendMessage.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [DynamoDB GetItem](./packages/alchemy/src/AWS/DynamoDB/GetItem.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [Kinesis PutRecord](./packages/alchemy/src/AWS/Kinesis/PutRecord.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [Lambda InvokeFunction](./packages/alchemy/src/AWS/Lambda/InvokeFunction.ts) — `Binding.Service` + `Binding.Policy`
|
||||
|
||||
For Event Sources, see:
|
||||
|
||||
- [SQS QueueEventSource](./packages/alchemy/src/AWS/SQS/QueueEventSource.ts)
|
||||
- [S3 BucketEventSource](./packages/alchemy/src/AWS/S3/BucketEventSource.ts)
|
||||
|
||||
The `Binding.Policy` implementation calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records binding data on the Stack. The `Binding.Service` implementation resolves the Policy via `yield* Policy(resource)`, then returns a typed callable that wraps the SDK client. At runtime, the Policy is not provided and becomes a no-op.
|
||||
|
||||
Each capability exports four things:
|
||||
|
||||
```ts
|
||||
// 1. The Binding.Service class
|
||||
export class PutRecord extends Binding.Service<...>()("AWS.Kinesis.PutRecord") {}
|
||||
|
||||
// 2. The Binding.Service Live layer (provided on Function Effect)
|
||||
export const PutRecordLive = Layer.effect(PutRecord, ...);
|
||||
|
||||
// 3. The Binding.Policy class
|
||||
export class PutRecordPolicy extends Binding.Policy<...>()("AWS.Kinesis.PutRecord") {}
|
||||
|
||||
// 4. The Binding.Policy Live layer (provided on Stack via AWS.providers()())
|
||||
export const PutRecordPolicyLive = Layer.effect(PutRecordPolicy, ...);
|
||||
```
|
||||
|
||||
### Runtime-only methods: color with `Alchemy.RuntimeContext`
|
||||
|
||||
The runtime callable returned by a `Binding.Service` (the inner Effect inside `.bind(resource)`'s return) **must** declare `Alchemy.RuntimeContext` as a requirement. This is how Alchemy models "this code can only run inside a deployed Function/Worker" at the type level — analogous to a colored function.
|
||||
|
||||
```ts
|
||||
import type { RuntimeContext } from "../../RuntimeContext.ts";
|
||||
|
||||
export class GetItem extends Binding.Service<
|
||||
GetItem,
|
||||
<T extends Table>(
|
||||
table: T,
|
||||
) => Effect.Effect<
|
||||
(
|
||||
request: GetItemRequest,
|
||||
) => Effect.Effect<
|
||||
DynamoDB.GetItemOutput,
|
||||
DynamoDB.GetItemError,
|
||||
RuntimeContext // ← runtime-only
|
||||
>
|
||||
>
|
||||
>()("AWS.DynamoDB.GetItem") {}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- **Outer Effect** (the `bind(resource)` setup) runs at the Function's init phase. It does NOT require `RuntimeContext`.
|
||||
- **Inner Effect** (the actual SDK invocation) only makes sense inside a running Function. It MUST require `RuntimeContext`.
|
||||
- Resolve cloud-environment services (`WorkerEnvironment`, AWS SDK clients, etc.) once during Layer construction and close over them. Do NOT leak `WorkerEnvironment` / `Lambda.FunctionEnvironment` onto the runtime callable — that couples downstream service code to a specific cloud and breaks Layer encapsulation. The Function/Worker runtime satisfies `RuntimeContext` automatically.
|
||||
- The implementation can return `Effect.Effect<A, E>` without explicitly providing `RuntimeContext` (it's contravariant in `R`); just declare it on the interface.
|
||||
|
||||
Why this matters: consumers can build cloud-agnostic services on top of bindings using `Layer.effect(Tag, ...)` without polluting their service interface with `WorkerEnvironment`. See [Layers concept](./website/src/content/docs/concepts/layers.mdx).
|
||||
|
||||
After implementing, register the Policy in `AWS.providers()()`:
|
||||
|
||||
- Add the `*PolicyLive` layer to `bindings()` in [Providers.ts](./packages/alchemy/src/AWS/Providers.ts)
|
||||
- Re-export from the service's `index.ts`
|
||||
|
||||
:::tip
|
||||
If you need to know what AWS region or account ID the resource is being created/updated in, you can use this inside any of the lifecycle operations.
|
||||
|
||||
```ts
|
||||
const region = yield * Region;
|
||||
const account = yield * Account;
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::warning
|
||||
You should favor getting the region/account INSIDE the lifecycle operations instead of inside the Layer effect like this because then it's scoped to the resource isntead of the resource provider:
|
||||
|
||||
```ts
|
||||
reconcile: Effect.fn(function* ({ id, news, output, session }) {
|
||||
const region = yield* Region;
|
||||
const accountId = yield* Account;
|
||||
});
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::warning
|
||||
Do not use `Effect.orDie` in the lifecycle operations since this will crash the whole IaC engine.
|
||||
:::
|
||||
|
||||
:::warning
|
||||
**Never use `async`/`await`, raw `Promise`, `node:fs/promises`, `node:fs`, `node:os`, or `pathe` directly in resource code.** Always use the Effect platform services so that effects remain composable, traceable, retryable, and testable:
|
||||
|
||||
| Don't | Do |
|
||||
| ---------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| `import fs from "node:fs/promises"` | `const fs = yield* FileSystem.FileSystem` |
|
||||
| `await fs.readFile(p, "utf8")` | `yield* fs.readFileString(p)` |
|
||||
| `await fs.mkdtemp(...)` | `yield* fs.makeTempDirectory({ prefix: ... })` |
|
||||
| `import path from "pathe"` / `node:path` | `const path = yield* Path.Path` |
|
||||
| `await fetch(...)` | `yield* HttpClient.HttpClient` + `HttpClientRequest` |
|
||||
| `Effect.promise(() => listSqlFiles(dir))` | Make `listSqlFiles` itself return `Effect` and `yield*` it |
|
||||
| `new Promise((res) => setTimeout(res, ms))` | `yield* Effect.sleep(Duration.millis(ms))` |
|
||||
|
||||
Sync, CPU-only Node APIs (e.g. `crypto.createHash().update().digest()`, `process.cwd()`, `Buffer`, `TextEncoder`) must still be wrapped in `Effect.sync(() => ...)` (or `Effect.try` if they can throw) so the call participates in the Effect runtime — tracing, interruption, and error channels. Don't call them as bare expressions inside `Effect.gen`.
|
||||
|
||||
```ts
|
||||
const hash = yield* Effect.sync(() =>
|
||||
crypto.createHash("sha256").update(input).digest("hex"),
|
||||
);
|
||||
const cwd = yield* Effect.sync(() => process.cwd());
|
||||
```
|
||||
|
||||
This applies to **lifecycle operations, helpers, AND tests**. Tests must use `FileSystem.FileSystem`/`Path.Path` for any file/path access (see [Database.test.ts](./packages/alchemy/test/Cloudflare/D1/Database.test.ts) for the pattern).
|
||||
:::
|
||||
|
||||
:::tip
|
||||
If a Resource supports tags, you should always include the internal Alchemy tags to brand the resource with the app, stage and logical ID so that we can "know" that we created it and are responsible for it.
|
||||
|
||||
```ts
|
||||
reconcile: Effect.fn(function* ({ id, news, output, session }) {
|
||||
const internalTags = yield* createInternalTags(id);
|
||||
const userTags = news.tags ?? {};
|
||||
const allTags = { ...internalTags, ...userTags };
|
||||
});
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::warning
|
||||
Do not roll your own tag diffing logic, always use `diffTags` from [Tags.ts](./packages/alchemy/src/Tags.ts), and diff against **observed cloud tags** (not `olds.tags` or `output.tags`). Adoption can hand you a resource whose tags don't match what we last persisted.
|
||||
|
||||
```ts
|
||||
reconcile: Effect.fn(function* ({ id, news, output, session }) {
|
||||
const internalTags = yield* createInternalTags(id);
|
||||
const newTags = { ...news.tags, ...internalTags };
|
||||
// Read tags fresh from the cloud so adoption (where tags may not match
|
||||
// what we last persisted) converges correctly.
|
||||
const oldTags = yield* fetchObservedTags(/* … */);
|
||||
// Option 1. use `upsert` if the API expects you to create/update tags in one call
|
||||
const { removed, upsert } = diffTags(oldTags, newTags);
|
||||
// Option 2. use `added` and `updated` if the API expects you to create/update tags in separate calls
|
||||
const { removed, added, updated } = diffTags(oldTags, newTags);
|
||||
// Option 3. use `upsert` only if the API doesn't expect you to remove tags (only PUT/UPDATe)
|
||||
const { upsert } = diffTags(oldTags, newTags);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
9. Implement the test cases in `packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts`.
|
||||
|
||||
Read through the established test cases before continuing so that you understand the pattern and structure of the test cases.
|
||||
|
||||
- [S3 Bucket Test Cases](./test/AWS/S3/Bucket.test.ts)
|
||||
- [SQS Queue Test Cases](./test/AWS/SQS/Queue.test.ts)
|
||||
- [Lambda Function Test Cases](./test/AWS/Lambda/Function.test.ts)
|
||||
- [Kinesis Stream Test Cases](./test/AWS/Kinesis/Stream.test.ts)
|
||||
- [DynamoDB Table Test Cases](./test/AWS/DynamoDB/Table.test.ts)
|
||||
- [VPC Test Cases](./test/AWS/EC2/Vpc.test.ts)
|
||||
- [Subnet Test Cases](./test/AWS/EC2/Subnet.test.ts)
|
||||
|
||||
:::warning
|
||||
Never use `Date.now()` when constructing the physical name of a resource. You should either:
|
||||
|
||||
1. Do not proide a name and rely on the resource provider to generate a unique name for you from the app, stage and logical ID.
|
||||
2. Construct a deterministic one unique to each test case. But it should be the same on each subsequent run of the test case.
|
||||
:::
|
||||
|
||||
3. Consider implementing an aggregate Smoke test that brings together multiple resources that are often used together.
|
||||
|
||||
See the [VPC Smoke Test](./test/AWS/EC2/Vpc.smoke.test.ts) for an example.
|
||||
|
||||
11. Add the resource-level JSDoc (`@section` + `@example` blocks) and field-level JSDoc on each prop/attribute on the source `.ts` file. Then run `bun generate:api-reference` to refresh `website/src/content/docs/providers/{Cloud}/{Resource}.md`. Do NOT manually edit the generated markdown.
|
||||
|
||||
# Test Fixtures for Effect-Native Workers / Functions
|
||||
|
||||
To test runtime behavior of an Effect-native Worker, Workflow, Lambda, etc., write a **fixture** that defines the Worker/Function with the bindings under test and exposes one HTTP route per behavior, then write a **test** that deploys the fixture once via `beforeAll` and drives it over HTTP.
|
||||
|
||||
## File system layout
|
||||
|
||||
Put fixtures in a `fixtures/` directory next to the test file. Each test suite owns its own fixtures — never reach across suites:
|
||||
|
||||
```sh
|
||||
packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts
|
||||
packages/alchemy/test/{Cloud}/{Service}/fixtures/{worker|workflow|handler}.ts
|
||||
```
|
||||
|
||||
## Fixture shape
|
||||
|
||||
Resolve the bindings, expose one route per behavior, default-export the class so the test can deploy it directly:
|
||||
|
||||
```ts
|
||||
// fixtures/worker.ts
|
||||
import * as Cloudflare from "@/Cloudflare/index.ts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { Gateway } from "./gateway.ts";
|
||||
|
||||
export default class TestWorker extends Cloudflare.Worker<TestWorker>()(
|
||||
"TestWorker",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const aiGateway = yield* Cloudflare.AiGateway.bind(Gateway);
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest;
|
||||
if (request.url.startsWith("/url")) {
|
||||
const url = yield* aiGateway.getUrl().pipe(Effect.orDie);
|
||||
return yield* HttpServerResponse.json({ url });
|
||||
}
|
||||
return HttpServerResponse.text("ok");
|
||||
}),
|
||||
};
|
||||
}).pipe(Effect.provide(Cloudflare.AiGatewayBindingLive)),
|
||||
) {}
|
||||
```
|
||||
|
||||
## Test shape
|
||||
|
||||
Compose a `Stack` that deploys the fixture, share one deploy across the file with `beforeAll`/`afterAll`, drive it via `HttpClient`, and retry the first request through edge propagation:
|
||||
|
||||
```ts
|
||||
// Service.test.ts
|
||||
import * as Alchemy from "@/index.ts";
|
||||
import * as Cloudflare from "@/Cloudflare";
|
||||
import * as Test from "@/Test/Vitest";
|
||||
import { expect } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import TestWorker from "./fixtures/worker.ts";
|
||||
|
||||
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
|
||||
providers: Cloudflare.providers(),
|
||||
});
|
||||
|
||||
const Stack = Alchemy.Stack(
|
||||
"ServiceTestStack",
|
||||
{ providers: Cloudflare.providers(), state: Cloudflare.state() },
|
||||
Effect.gen(function* () {
|
||||
const worker = yield* TestWorker;
|
||||
return { url: worker.url.as<string>() };
|
||||
}),
|
||||
);
|
||||
|
||||
const stack = beforeAll(deploy(Stack));
|
||||
afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
|
||||
|
||||
test(
|
||||
"deployed worker exercises the binding",
|
||||
Effect.gen(function* () {
|
||||
const { url } = yield* stack;
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
|
||||
const res = yield* client.get(`${url}/url`).pipe(
|
||||
Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 10 }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (yield* res.json) as { url: string };
|
||||
expect(body.url).toContain("gateway.ai.cloudflare.com");
|
||||
}),
|
||||
{ timeout: 180_000 },
|
||||
);
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `Test.make({ providers: Cloudflare.providers() })` gives you `test`, `beforeAll`, `afterAll`, `deploy`, `destroy`.
|
||||
- `beforeAll(deploy(Stack))` returns a handle (`stack` above) that every `test` body can `yield*` to get the stack outputs.
|
||||
- `afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack))` is the standard cleanup — set `NO_DESTROY=1` locally to keep the deployment around between runs while iterating.
|
||||
- Always retry the first request (`Schedule.exponential("500 millis")`) — fresh workers.dev URLs and Lambda function URLs take a few seconds to start serving 200s.
|
||||
- For POST: use `client.post(url)` for empty bodies, or `HttpClient.execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)))` for typed bodies.
|
||||
- **Never use `while (Date.now() < deadline)` loops to poll** for an async side effect (a workflow status, a cron fire, a queue drain, eventual-consistency read, etc.). Use `Effect.repeat` with a `Schedule` and an `until` predicate so the polling participates in the Effect runtime — tracing, interruption, and error propagation work correctly, and the intent is declarative. Cap iterations with `times: N` (or a bounded schedule) so the test fails fast instead of running until the vitest timeout:
|
||||
|
||||
```ts
|
||||
// good — declarative, bounded, interruption-safe
|
||||
const value = yield* fetchValue.pipe(
|
||||
Effect.repeat({
|
||||
schedule: Schedule.spaced("5 seconds"),
|
||||
until: (v) => v.ready,
|
||||
times: 36,
|
||||
}),
|
||||
);
|
||||
|
||||
// bad — opaque loop, ignores interruption, leaks into vitest timeout
|
||||
let value: Value | undefined;
|
||||
const deadline = Date.now() + 180_000;
|
||||
while (Date.now() < deadline) {
|
||||
value = yield* fetchValue;
|
||||
if (value.ready) break;
|
||||
yield* Effect.sleep("5 seconds");
|
||||
}
|
||||
```
|
||||
|
||||
See [CronEventSource.test.ts](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) for a real-world example (polling a DO via the worker's `/times` route until the cron handler fires).
|
||||
|
||||
## Reference implementations
|
||||
|
||||
- Cloudflare AiGateway — [worker fixture](./packages/alchemy/test/Cloudflare/AiGateway/worker.ts) + [test](./packages/alchemy/test/Cloudflare/AiGateway/AiGateway.test.ts) (the deploy+fetch case lives at the bottom of the file)
|
||||
- Cloudflare D1Connection — [worker fixture](./packages/alchemy/test/Cloudflare/D1/d1-worker.ts) + [test](./packages/alchemy/test/Cloudflare/D1/D1Binding.test.ts)
|
||||
- Cloudflare Workflow — [workflow fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/test-workflow.ts) + [worker fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/workflow-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/Workflow.test.ts)
|
||||
- Cloudflare Cron Trigger — [worker + DO fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/cron-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) (cron handler writes to a DO; test polls a fetch route with `Effect.repeat` until the scheduled handler fires)
|
||||
- Cloudflare Images — [effect fixture](./packages/alchemy/test/Cloudflare/Images/fixtures/effect-worker.ts) + [async fixture](./packages/alchemy/test/Cloudflare/Images/fixtures/async-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Images/Images.test.ts)
|
||||
- AWS Lambda (DynamoDB bindings) — [Lambda fixture](./packages/alchemy/test/AWS/DynamoDB/handler.ts) + [test](./packages/alchemy/test/AWS/DynamoDB/Bindings.test.ts) (one `describe("<BindingName>")` per binding, all driving the same deployed Lambda)
|
||||
|
||||
# Spec-Driven Service Bring-Up
|
||||
|
||||
Use @processes/AWS.md as the source of truth for bringing a single AWS service from zero to full coverage.
|
||||
|
||||
That process covers:
|
||||
|
||||
- deriving resources, bindings, event sources, and helpers from distilled
|
||||
- the audit-driven implementation loop
|
||||
- deterministic checks for registration and binding test coverage
|
||||
- Lambda fixture testing conventions
|
||||
- learned conventions like no auto-marshalling and one `describe("<BindingName>")` block per binding
|
||||
|
||||
Keep `AGENTS.md` high-level and update @processes/AWS.md when the process evolves.
|
||||
|
||||
When a canonical resource needs mutable event-source configuration and there is any chance of circularity, prefer a resource binding contract over a plain input prop. DynamoDB Streams is the reference case: `Table` owns the actual stream state, while `streams(table)` injects that state via bindings and the runtime-specific layer handles the subscription mechanics. See @processes/AWS.md for the DynamoDB Streams case study.
|
||||
|
||||
# Build and Type Checking
|
||||
|
||||
Always run type checking before committing changes:
|
||||
|
||||
```bash
|
||||
bun tsc -b
|
||||
```
|
||||
|
||||
This runs the TypeScript compiler in build mode, which checks all projects in the workspace. This is critical because CI will fail if there are type errors.
|
||||
|
||||
## Build Commands
|
||||
|
||||
| Command | Description |
|
||||
| ----------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `bun tsc -b` | Type check all projects (always run before committing) |
|
||||
| `bun run build` | Clean, type check, and build the alchemy package |
|
||||
| `bun build:clean` | Full clean rebuild: cleans all artifacts, reinstalls dependencies, builds, and downloads env |
|
||||
|
||||
Use `bun build:clean` when you encounter stale build artifacts or dependency issues. It runs:
|
||||
|
||||
1. `bun clean .` - Removes all untracked files except .env
|
||||
2. `bun i` - Reinstalls dependencies
|
||||
3. `bun run build` - Builds the project
|
||||
4. `bun download:env` - Downloads environment files
|
||||
|
||||
# Tutorial Documentation Standard
|
||||
|
||||
Tutorials under `website/src/content/docs/tutorial/` are **step-by-step and granular**: every code snippet introduces exactly **one** new thing, followed by a short prose explanation of just that thing. Each step gets its own `##` heading.
|
||||
|
||||
**Anti-pattern** — one snippet that adds multiple distinct changes, followed by a numbered list or bullet list explaining each:
|
||||
|
||||
````md
|
||||
## Bind the DO to the Worker
|
||||
|
||||
```diff lang="typescript"
|
||||
+import Counter from "./counter.ts";
|
||||
+import { HttpServerRequest } from "...";
|
||||
|
||||
Effect.gen(function* () {
|
||||
+ const counters = yield* Counter;
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
+ const request = yield* HttpServerRequest;
|
||||
+ if (request.url.startsWith("/counter/") && ...) {
|
||||
+ const next = yield* counters.getByName(name).increment();
|
||||
+ return HttpServerResponse.text(String(next));
|
||||
+ }
|
||||
return HttpServerResponse.text("Hello!");
|
||||
}),
|
||||
};
|
||||
})
|
||||
```
|
||||
|
||||
Two things just happened:
|
||||
1. `yield* Counter` registers the DO ...
|
||||
2. `counters.getByName(name)` returns a typed stub ...
|
||||
````
|
||||
|
||||
**Correct** — split into one heading per step, each with one snippet and one explanation:
|
||||
|
||||
````md
|
||||
## Bind the DO to the Worker
|
||||
|
||||
```diff lang="typescript"
|
||||
+import Counter from "./counter.ts";
|
||||
|
||||
Effect.gen(function* () {
|
||||
+ const counters = yield* Counter;
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
`yield* Counter` registers the DO with the Worker (binding + class-migration metadata) and hands you the namespace.
|
||||
|
||||
## Call the DO from `fetch`
|
||||
|
||||
```diff lang="typescript"
|
||||
+import { HttpServerRequest } from "...";
|
||||
|
||||
fetch: Effect.gen(function* () {
|
||||
+ const request = yield* HttpServerRequest;
|
||||
+ if (request.url.startsWith("/counter/") && ...) {
|
||||
+ const next = yield* counters.getByName(name).increment();
|
||||
+ return HttpServerResponse.text(String(next));
|
||||
+ }
|
||||
return HttpServerResponse.text("Hello!");
|
||||
})
|
||||
```
|
||||
|
||||
`counters.getByName(name)` returns a typed stub — `increment()` and `get()` round-trip through Cloudflare's RPC machinery.
|
||||
````
|
||||
|
||||
Rules of thumb:
|
||||
|
||||
- If you find yourself writing "Two/three things just happened", "A few things are happening here", or a numbered/bulleted list explaining separate parts of a single snippet — **split the snippet**.
|
||||
- One concept ⇒ one heading ⇒ one diff snippet ⇒ one explanation paragraph (no bullets).
|
||||
- Bullet/numbered lists are fine when they describe a recap, prerequisites, or genuinely list-shaped content (e.g. "the Worker now handles two routes: PUT and GET" at the end). They are **not** fine as a substitute for splitting a compound snippet.
|
||||
- A single API call that internally does several things (e.g. `Cloudflare.upgrade()`) doesn't need splitting — describe its behavior in prose.
|
||||
- Use `diff lang="typescript"` blocks so each step shows what's added on top of the previous step.
|
||||
|
||||
# Pull Request Conventions
|
||||
|
||||
When you automatically open a PR, it MUST follow this structure:
|
||||
|
||||
- **Title**: Use conventional commit format (e.g. `fix(website): mobile theme metas`, `feat(aws/s3): add bucket lifecycle rules`).
|
||||
- **Description heading levels**: NEVER use `#` or `##` in the PR description. The smallest heading allowed is `###`. The PR description must NOT begin with its own title heading — GitHub already renders the PR title above it.
|
||||
- **Content**: Aim for the minimal content needed to convey the idea.
|
||||
- Use simple sentences. If there are multiple discrete changes, use bullet points.
|
||||
- **Prefer code snippets over prose.** A short ` ```ts ` or ` ```diff ` block showing the new/changed shape is worth more than a paragraph explaining it. Reach for code first; only add prose to fill in the "why" the snippet can't show on its own.
|
||||
- Be direct and succinct. Cut adjectives, justifications, and anything that reads like marketing copy. If a sentence is restating what the diff already shows, delete it.
|
||||
- **Never include a "Test plan", "Testing", or checklist of TODOs.** PR descriptions document the change, not the verification process. If something needs manual verification, follow the draft-PR rule below.
|
||||
- Skip examples for trivial fixes, internal refactors, or doc-only changes.
|
||||
|
||||
Example PR description (good — code snippet does the talking):
|
||||
|
||||
````
|
||||
Track which state-store backend each project uses by emitting a `state_store.init` span tagged with `alchemy.state_store.kind`.
|
||||
|
||||
```ts
|
||||
// every Layer.effect(State, …) site now wraps construction:
|
||||
makeLocalState().pipe(recordStateStoreInit("local"))
|
||||
```
|
||||
|
||||
Dashboard groups projects by kind from these spans (Axiom can't APL-query metric datasets).
|
||||
````
|
||||
- **Outstanding work / testing / review needed**: If there are outstanding steps, manual testing required, or review items, DO NOT leave a comment on the PR and DO NOT include them in the PR description. Instead:
|
||||
1. Mark the PR as **draft**.
|
||||
2. Tell the user (in the chat that initiated the PR creation) what is outstanding.
|
||||
|
||||
:::warning
|
||||
**Markdown content must reach GitHub verbatim** — un-escaped backticks, fenced code blocks, etc. The reliable shape is to write the description to a file and pass `--body-file <path>` to `gh pr create` / `gh pr edit`:
|
||||
|
||||
```sh
|
||||
# write the body to a temp file (use Write tool, not echo/cat heredoc)
|
||||
gh pr edit 179 --body-file /tmp/pr-body.md
|
||||
```
|
||||
|
||||
Do **not** inline the body via `--body "$(cat <<'EOF' ... EOF)"`. Even with a single-quoted heredoc some shells / `gh` versions still mangle backticks and backslashes; the resulting PR body ends up with literal `\`` sequences instead of inline code spans. `--body-file` sidesteps shell quoting entirely.
|
||||
|
||||
If you need to update an already-created PR's body, prefer `gh pr edit --body-file ...`. If that silently no-ops (older `gh` versions), fall back to `gh api -X PATCH repos/<owner>/<repo>/pulls/<n> -F body=@/tmp/pr-body.md`.
|
||||
:::
|
||||
|
||||
The summary goes at the very top of the description as plain prose — NO heading above it, no `### Summary`, nothing. The PR title already serves as the title; do not repeat or re-title it. Only add `###` subheadings further down if the description genuinely has multiple sections worth separating.
|
||||
|
||||
Example PR description (good):
|
||||
|
||||
```
|
||||
Persist the user's selected theme across reloads and fix a hero scroll glitch on mobile.
|
||||
|
||||
- Read theme from `localStorage` on mount before first paint
|
||||
- Add `<meta name="theme-color">` per theme so mobile chrome matches
|
||||
```
|
||||
|
||||
Example PR description (BAD — do not do this):
|
||||
|
||||
```
|
||||
## Theme persistence fix ← no, the PR title already exists
|
||||
### Summary ← no, summary needs no heading
|
||||
Persist the user's theme...
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,85 @@
|
||||
<div align="center">
|
||||
|
||||
<a href="https://v2.alchemy.run">
|
||||
<img src="./images/readme-hero.png" alt="Alchemy — Infrastructure as Effects" width="360" />
|
||||
</a>
|
||||
|
||||
<br />
|
||||
|
||||
[](https://www.npmjs.com/package/alchemy)
|
||||
[](./LICENSE)
|
||||
[](https://discord.gg/jwKw8dBJdN)
|
||||
|
||||
**Infrastructure-as-Effects** — cloud infrastructure and application logic as a single, type-safe [Effect](https://effect.website) program.
|
||||
|
||||
[Docs](https://v2.alchemy.run) · [Tutorial](https://v2.alchemy.run/tutorial/part-1) · [Examples](./examples) · [Discord](https://discord.gg/jwKw8dBJdN)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
A Worker bound to a R2 bucket and serving objects from it:
|
||||
|
||||
```typescript
|
||||
const Bucket = Cloudflare.R2Bucket("bucket");
|
||||
|
||||
export default Cloudflare.Worker(
|
||||
"api",
|
||||
{ main: import.meta.path },
|
||||
Effect.gen(function* () {
|
||||
const bucket = yield* Cloudflare.R2Bucket.bind(Bucket);
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest;
|
||||
const object = yield* bucket.get(request.url);
|
||||
return HttpServerResponse.stream(object!.body);
|
||||
})
|
||||
};
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
One `bind()` wires the binding, env var, and typed connection — at deploy time and at runtime.
|
||||
|
||||
---
|
||||
|
||||
- **One program, one language.** Resources, Lambdas/Workers, IAM, and SDKs live in the same Effect program — no YAML, no second runtime.
|
||||
- **Bindings, not glue code.** `S3.GetObject.bind(bucket)` wires the IAM policy, env var, and a typed SDK call in a single line.
|
||||
- **Errors in the type system.** Every cloud API failure is a tagged Effect error you handle — or don't — on purpose.
|
||||
- **AWS + Cloudflare today.** S3, SQS, DynamoDB, Kinesis, Lambda, EC2 / Workers, R2, D1, Durable Objects, Containers.
|
||||
- **Same code, every stage.** Local dev, `plan` / `deploy`, smoke tests, and CI all share one mental model.
|
||||
|
||||
```sh
|
||||
bun add alchemy effect
|
||||
```
|
||||
|
||||
## Bootstrap with an AI coding agent
|
||||
|
||||
Paste this into Claude Code, Cursor, or any agent that can fetch a URL:
|
||||
|
||||
```
|
||||
You are an Alchemy expert. Read https://v2.alchemy.run/llms.txt to load the
|
||||
full documentation index, then act as my pair on this project.
|
||||
|
||||
Goal: help me set up, build, test, and deploy a cloud application with
|
||||
`alchemy` (Infrastructure-as-Effects, powered by Effect).
|
||||
|
||||
Follow the patterns from the docs and the /examples folder. Stay idiomatic
|
||||
to Effect: use Layers for wiring, return Effects from lifecycle code, and
|
||||
keep infra and runtime in the same program. Ask before introducing new
|
||||
dependencies or breaking conventions.
|
||||
```
|
||||
|
||||
## Learn more
|
||||
|
||||
- [What is Alchemy?](https://v2.alchemy.run/what-is-alchemy) — the framework in 2 minutes
|
||||
- [Getting Started](https://v2.alchemy.run/getting-started) — your first Stack
|
||||
- [Tutorial](https://v2.alchemy.run/tutorial/part-1) — five-part walkthrough to a tested, CI-deployed app
|
||||
- [Examples](./examples) — runnable projects on AWS and Cloudflare
|
||||
- [llms.txt](https://v2.alchemy.run/llms.txt) — agent-ready documentation index
|
||||
|
||||
> **alchemy** is in alpha. Expect breaking changes. Come hang in our [Discord](https://discord.gg/jwKw8dBJdN).
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { NetworkLive } from "./src/Network.ts";
|
||||
import Server from "./src/Server.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsEc2Example",
|
||||
{ providers: aws, state: Alchemy.localState() },
|
||||
Effect.gen(function* () {
|
||||
const instance = yield* Server;
|
||||
|
||||
return {
|
||||
instanceId: instance.instanceId,
|
||||
publicIpAddress: instance.publicIpAddress,
|
||||
instanceUrl: Output.interpolate`http://${instance.publicIpAddress}:3000`,
|
||||
enqueueExample: Output.interpolate`http://${instance.publicIpAddress}:3000/enqueue?message=hello`,
|
||||
};
|
||||
}).pipe(Effect.provide(NetworkLive)),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-ec2-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-ec2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import type { Output } from "alchemy/Output";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export interface ExampleNetwork {
|
||||
network: AWS.EC2.Network;
|
||||
publicSubnetIds: Output<AWS.EC2.SubnetId>[];
|
||||
appSecurityGroupId: Output<AWS.EC2.SecurityGroupId>;
|
||||
}
|
||||
|
||||
export class Network extends Context.Service<Network, ExampleNetwork>()(
|
||||
"Network",
|
||||
) {}
|
||||
|
||||
export const NetworkLive = Layer.effect(
|
||||
Network,
|
||||
Effect.gen(function* () {
|
||||
const network = yield* AWS.EC2.Network("Network", {
|
||||
cidrBlock: "10.42.0.0/16",
|
||||
availabilityZones: 2,
|
||||
nat: "single",
|
||||
});
|
||||
|
||||
const appSecurityGroup = yield* AWS.EC2.SecurityGroup("AppSecurityGroup", {
|
||||
vpcId: network.vpcId,
|
||||
description: "Security group for the EC2 application instance",
|
||||
ingress: [
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 3000,
|
||||
toPort: 3000,
|
||||
cidrIpv4: "0.0.0.0/0",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
network,
|
||||
publicSubnetIds: network.publicSubnetIds,
|
||||
appSecurityGroupId: appSecurityGroup.groupId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import { SQSQueueEventSource } from "alchemy/Server/SQSQueueEventSource";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { Network, NetworkLive } from "./Network.ts";
|
||||
|
||||
export default class Server extends AWS.EC2.Instance<Server>()(
|
||||
"ServerInstance",
|
||||
Effect.gen(function* () {
|
||||
const imageId = yield* AWS.EC2.amazonLinux();
|
||||
const network = yield* Network;
|
||||
|
||||
return {
|
||||
main: import.meta.filename,
|
||||
imageId,
|
||||
instanceType: "t3.small",
|
||||
subnetId: network.publicSubnetIds[0],
|
||||
securityGroupIds: [network.appSecurityGroupId],
|
||||
associatePublicIpAddress: true,
|
||||
port: 3000,
|
||||
};
|
||||
}),
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* AWS.SQS.Queue("JobsQueue", {
|
||||
receiveMessageWaitTimeSeconds: 20,
|
||||
visibilityTimeout: 60,
|
||||
});
|
||||
|
||||
yield* AWS.SQS.messages(queue).subscribe((stream) =>
|
||||
stream.pipe(Stream.mapEffect(Effect.logInfo), Stream.runDrain),
|
||||
);
|
||||
|
||||
const sendMessage = yield* AWS.SQS.SendMessage.bind(queue);
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = new URL(request.originalUrl);
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/") {
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
routes: ["GET /", "GET /enqueue?message=hello"],
|
||||
});
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/enqueue") {
|
||||
const message = url.searchParams.get("message") ?? "hello from EC2";
|
||||
const body = JSON.stringify({
|
||||
message,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const result = yield* sendMessage({
|
||||
MessageBody: body,
|
||||
});
|
||||
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
message,
|
||||
messageId: result.MessageId,
|
||||
});
|
||||
}
|
||||
|
||||
return HttpServerResponse.text("Not found", { status: 404 });
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(
|
||||
HttpServerResponse.text("Internal server error", { status: 500 }),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(NetworkLive, SQSQueueEventSource),
|
||||
Layer.mergeAll(
|
||||
AWS.SQS.DeleteMessageBatchLive,
|
||||
AWS.SQS.ReceiveMessageLive,
|
||||
AWS.SQS.SendMessageLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import QueueConsumerTask from "./src/QueueConsumerTask.ts";
|
||||
import ApiTask from "./src/Task.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsEcsExample",
|
||||
{
|
||||
providers: aws,
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const network = yield* AWS.EC2.Network("ExampleNetwork", {
|
||||
cidrBlock: "10.42.0.0/16",
|
||||
availabilityZones: 2,
|
||||
});
|
||||
|
||||
const serviceSecurityGroup = yield* AWS.EC2.SecurityGroup(
|
||||
"ExampleServiceSecurityGroup",
|
||||
{
|
||||
vpcId: network.vpcId,
|
||||
description: "Security group for the ECS example services",
|
||||
ingress: [
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 80,
|
||||
toPort: 80,
|
||||
cidrIpv4: "0.0.0.0/0",
|
||||
},
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 3000,
|
||||
toPort: 3000,
|
||||
cidrIpv4: "0.0.0.0/0",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const queue = yield* AWS.SQS.Queue("ExampleJobsQueue", {
|
||||
receiveMessageWaitTimeSeconds: 20,
|
||||
visibilityTimeout: 60,
|
||||
});
|
||||
|
||||
const cluster = yield* AWS.ECS.Cluster("ExampleCluster", {});
|
||||
const apiTask = yield* ApiTask;
|
||||
const queuePollerTask = yield* QueueConsumerTask;
|
||||
|
||||
const apiService = yield* AWS.ECS.Service("ExampleApiService", {
|
||||
cluster,
|
||||
task: apiTask,
|
||||
vpcId: network.vpcId,
|
||||
subnets: network.publicSubnetIds,
|
||||
securityGroups: [serviceSecurityGroup.groupId],
|
||||
assignPublicIp: true,
|
||||
public: true,
|
||||
healthCheckPath: "/",
|
||||
});
|
||||
|
||||
yield* AWS.ECS.Service("ExampleQueuePollerService", {
|
||||
cluster,
|
||||
task: queuePollerTask,
|
||||
vpcId: network.vpcId,
|
||||
subnets: network.publicSubnetIds,
|
||||
securityGroups: [serviceSecurityGroup.groupId],
|
||||
assignPublicIp: true,
|
||||
desiredCount: 1,
|
||||
});
|
||||
|
||||
return {
|
||||
url: apiService.url,
|
||||
queueUrl: queue.queueUrl,
|
||||
enqueueExample: Output.interpolate`${apiService.url}/enqueue?message=hello`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-ecs-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-ecs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
/**
|
||||
* Deploy-time binding for the ECS example’s jobs queue. Provide with
|
||||
* `Layer.succeed(ExampleJobsQueue, queue)` from the stack after the queue exists.
|
||||
*/
|
||||
export class JobsQueue extends Context.Service<JobsQueue, AWS.SQS.Queue>()(
|
||||
"JobsQueue",
|
||||
) {}
|
||||
|
||||
export const JobsQueueLive = Layer.effect(
|
||||
JobsQueue,
|
||||
AWS.SQS.Queue("JobsQueue"),
|
||||
);
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Server from "alchemy/Server";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { JobsQueue, JobsQueueLive } from "./JobsQueue.ts";
|
||||
|
||||
export default class QueueConsumerTask extends AWS.ECS.Task<QueueConsumerTask>()(
|
||||
"QueueConsumerTask",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
cpu: 256,
|
||||
memory: 512,
|
||||
taskRoleManagedPolicyArns: ["arn:aws:iam::aws:policy/AmazonSQSFullAccess"],
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* JobsQueue;
|
||||
yield* AWS.SQS.messages(queue, {
|
||||
batchSize: 10,
|
||||
maximumBatchingWindowInSeconds: 20,
|
||||
}).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.runForEach((record) =>
|
||||
Effect.logInfo(
|
||||
`processed SQS message ${record.messageId}: ${record.body ?? ""}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(Server.SQSQueueEventSource, JobsQueueLive),
|
||||
Layer.mergeAll(
|
||||
AWS.SQS.ReceiveMessageLive,
|
||||
AWS.SQS.DeleteMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,67 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { JobsQueue, JobsQueueLive } from "./JobsQueue.ts";
|
||||
|
||||
export default class ApiTask extends AWS.ECS.Task<ApiTask>()(
|
||||
"ApiTask",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
cpu: 512,
|
||||
memory: 1024,
|
||||
port: 3000,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* JobsQueue;
|
||||
const sendMessage = yield* AWS.SQS.SendMessage.bind(queue);
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = new URL(request.originalUrl);
|
||||
if (request.method === "GET" && url.pathname === "/") {
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
routes: ["GET /", "GET /enqueue?message=hello"],
|
||||
});
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/enqueue") {
|
||||
const message = url.searchParams.get("message") ?? "hello from ECS";
|
||||
const body = JSON.stringify({
|
||||
message,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const result = yield* sendMessage({
|
||||
MessageBody: body,
|
||||
});
|
||||
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
message,
|
||||
messageId: result.MessageId,
|
||||
});
|
||||
}
|
||||
|
||||
return HttpServerResponse.text("Not found", { status: 404 });
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(
|
||||
HttpServerResponse.text("Internal server error", { status: 500 }),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
JobsQueueLive,
|
||||
AWS.SQS.SendMessageLive,
|
||||
AWS.SQS.DeleteMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# AWS EKS Auto Mode Example
|
||||
|
||||
This example is fully TypeScript-driven. It provisions:
|
||||
|
||||
- `AWS.EC2.Network`
|
||||
- `AWS.EKS.AutoCluster`
|
||||
- `AWS.EKS.AccessEntry` for cluster-admin access
|
||||
- `AWS.EKS.Addon` for `metrics-server` and `snapshot-controller`
|
||||
- `AWS.EKS.LoadBalancedWorkload` for deployment + public service composition
|
||||
- `AWS.EKS.PodIdentityWorkload` for workload identity + deployment composition
|
||||
- `Kubernetes.Namespace`
|
||||
- `Kubernetes.Job`
|
||||
|
||||
There is no YAML or `kubectl apply` step. The workloads are declared in
|
||||
[`alchemy.run.ts`](./alchemy.run.ts) and reconciled by the EKS cluster resource.
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
bun install
|
||||
bun run --filter aws-eks-example deploy
|
||||
bun run --filter aws-eks-example destroy
|
||||
```
|
||||
|
||||
## Cluster Access
|
||||
|
||||
By default, the example grants cluster-admin access to the IAM principal that is
|
||||
running the deploy. If your current caller is not a normal IAM user or IAM role,
|
||||
set this before deploy:
|
||||
|
||||
```sh
|
||||
export EKS_ADMIN_PRINCIPAL_ARN=arn:aws:iam::123456789012:role/YourAdminRole
|
||||
```
|
||||
|
||||
## What Gets Deployed
|
||||
|
||||
The example creates these in-cluster workloads in code:
|
||||
|
||||
- a `demo` namespace
|
||||
- an `echo-server` workload created with `AWS.EKS.LoadBalancedWorkload`
|
||||
- a `pod-identity-demo` workload created with `AWS.EKS.PodIdentityWorkload`
|
||||
- a `cluster-info` job
|
||||
|
||||
The pod identity workload creates the Kubernetes service account, IAM role,
|
||||
`AWS.EKS.PodIdentityAssociation`, and deployment together.
|
||||
|
||||
## Optional Inspection
|
||||
|
||||
If you want to inspect the cluster manually after deploy, you can still use your
|
||||
normal kubeconfig flow, for example:
|
||||
|
||||
```sh
|
||||
aws eks update-kubeconfig --name alchemy-eks-auto-example --region "$AWS_REGION"
|
||||
kubectl get pods -n demo
|
||||
```
|
||||
@@ -0,0 +1,251 @@
|
||||
import * as STS from "@distilled.cloud/aws/sts";
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as EC2 from "alchemy/AWS/EC2";
|
||||
import * as EKS from "alchemy/AWS/EKS";
|
||||
import * as Kubernetes from "alchemy/Kubernetes";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
const EKS_ADMIN_PRINCIPAL_ARN = Config.string("EKS_ADMIN_PRINCIPAL_ARN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
);
|
||||
|
||||
const clusterName = "alchemy-eks-auto-example";
|
||||
const namespace = "demo";
|
||||
const serviceAccount = "pod-identity-demo";
|
||||
|
||||
const toIamPrincipalArn = (arn: string): string | undefined => {
|
||||
const assumedRole = arn.match(
|
||||
/^arn:([^:]+):sts::([0-9]{12}):assumed-role\/(.+)\/[^/]+$/,
|
||||
);
|
||||
if (assumedRole) {
|
||||
const [, partition, accountId, rolePath] = assumedRole;
|
||||
return `arn:${partition}:iam::${accountId}:role/${rolePath}`;
|
||||
}
|
||||
|
||||
if (arn.includes(":role/") || arn.includes(":user/")) {
|
||||
return arn;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const resolveClusterAdminPrincipalArn = Effect.gen(function* () {
|
||||
const configured = yield* EKS_ADMIN_PRINCIPAL_ARN;
|
||||
if (configured) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
const caller = yield* STS.getCallerIdentity({});
|
||||
const principalArn =
|
||||
typeof caller.Arn === "string" ? toIamPrincipalArn(caller.Arn) : undefined;
|
||||
|
||||
if (!principalArn) {
|
||||
return yield* Effect.fail(
|
||||
new Error(
|
||||
"Unable to infer an IAM principal ARN for cluster access. Set EKS_ADMIN_PRINCIPAL_ARN before deploy.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return principalArn;
|
||||
});
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsEksExample",
|
||||
{
|
||||
providers: aws,
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const tags = {
|
||||
Example: "aws-eks",
|
||||
Surface: "eks",
|
||||
Mode: "auto",
|
||||
};
|
||||
|
||||
const clusterAdminPrincipalArn = yield* resolveClusterAdminPrincipalArn;
|
||||
|
||||
const network = yield* EC2.Network("Network", {
|
||||
cidrBlock: "10.42.0.0/16",
|
||||
availabilityZones: 2,
|
||||
nat: "single",
|
||||
tags,
|
||||
});
|
||||
|
||||
const cluster = yield* EKS.AutoCluster("Cluster", {
|
||||
clusterName,
|
||||
network,
|
||||
tags,
|
||||
});
|
||||
|
||||
const clusterAdmin = yield* EKS.AccessEntry("ClusterAdmin", {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
principalArn: clusterAdminPrincipalArn,
|
||||
accessPolicies: [
|
||||
{
|
||||
policyArn:
|
||||
"arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy",
|
||||
accessScope: {
|
||||
type: "cluster",
|
||||
},
|
||||
},
|
||||
],
|
||||
tags,
|
||||
});
|
||||
|
||||
const metricsServer = yield* EKS.Addon("MetricsServer", {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
addonName: "metrics-server",
|
||||
tags,
|
||||
});
|
||||
|
||||
const snapshotController = yield* EKS.Addon("SnapshotController", {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
addonName: "snapshot-controller",
|
||||
tags,
|
||||
});
|
||||
|
||||
const demoNamespace = yield* Kubernetes.Namespace("DemoNamespace", {
|
||||
cluster: cluster.cluster,
|
||||
name: namespace,
|
||||
labels: {
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
});
|
||||
|
||||
const echoServer = yield* EKS.LoadBalancedWorkload("EchoServer", {
|
||||
cluster: cluster.cluster,
|
||||
namespace: demoNamespace,
|
||||
name: "echo-server",
|
||||
labels: {
|
||||
"app.kubernetes.io/name": "echo-server",
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
replicas: 2,
|
||||
containers: [
|
||||
{
|
||||
name: "echo-server",
|
||||
image: "registry.k8s.io/echoserver:1.10",
|
||||
ports: [
|
||||
{
|
||||
containerPort: 8080,
|
||||
name: "http",
|
||||
},
|
||||
],
|
||||
resources: {
|
||||
requests: {
|
||||
cpu: "50m",
|
||||
memory: "64Mi",
|
||||
},
|
||||
limits: {
|
||||
cpu: "250m",
|
||||
memory: "128Mi",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
ports: [
|
||||
{
|
||||
name: "http",
|
||||
port: 80,
|
||||
targetPort: 8080,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const podIdentityWorkload = yield* EKS.PodIdentityWorkload(
|
||||
"PodIdentityDemo",
|
||||
{
|
||||
cluster: cluster.cluster,
|
||||
namespace: demoNamespace,
|
||||
name: "pod-identity-demo",
|
||||
serviceAccountName: serviceAccount,
|
||||
tags,
|
||||
serviceAccountLabels: {
|
||||
"app.kubernetes.io/name": serviceAccount,
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
labels: {
|
||||
"app.kubernetes.io/name": "pod-identity-demo",
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
containers: [
|
||||
{
|
||||
name: "aws-cli",
|
||||
image: "public.ecr.aws/aws-cli/aws-cli:2.17.37",
|
||||
command: ["/bin/sh", "-lc"],
|
||||
args: [
|
||||
[
|
||||
"while true; do",
|
||||
" date;",
|
||||
" aws sts get-caller-identity;",
|
||||
" sleep 60;",
|
||||
"done",
|
||||
].join(" "),
|
||||
],
|
||||
resources: {
|
||||
requests: {
|
||||
cpu: "50m",
|
||||
memory: "64Mi",
|
||||
},
|
||||
limits: {
|
||||
cpu: "250m",
|
||||
memory: "128Mi",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const clusterInfoJob = yield* Kubernetes.Job("ClusterInfoJob", {
|
||||
cluster: cluster.cluster,
|
||||
namespace: demoNamespace,
|
||||
name: "cluster-info",
|
||||
labels: {
|
||||
"app.kubernetes.io/name": "cluster-info",
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
containers: [
|
||||
{
|
||||
name: "cluster-info",
|
||||
image: "public.ecr.aws/docker/library/busybox:1.36",
|
||||
command: ["/bin/sh", "-lc"],
|
||||
args: [
|
||||
[
|
||||
'echo "demo workload is running on EKS Auto Mode";',
|
||||
"nslookup echo-server.demo.svc.cluster.local || true;",
|
||||
].join(" "),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
clusterArn: cluster.cluster.clusterArn,
|
||||
endpoint: cluster.cluster.endpoint,
|
||||
adminPrincipalArn: clusterAdmin.principalArn,
|
||||
namespace: demoNamespace.name,
|
||||
serviceAccount: podIdentityWorkload.serviceAccount.name,
|
||||
podIdentityAssociationArn:
|
||||
podIdentityWorkload.podIdentityAssociation.associationArn,
|
||||
workloadRoleArn: podIdentityWorkload.roleArn,
|
||||
metricsServerAddonArn: metricsServer.addonArn,
|
||||
snapshotControllerAddonArn: snapshotController.addonArn,
|
||||
echoDeploymentName: echoServer.deployment.name,
|
||||
echoServiceName: echoServer.service?.name,
|
||||
podIdentityDeploymentName: podIdentityWorkload.deployment.name,
|
||||
clusterInfoJobName: clusterInfoJob.name,
|
||||
accessSummary: Output.interpolate`Granted cluster-admin access on ${cluster.cluster.clusterName} to ${clusterAdmin.principalArn}.`,
|
||||
workloadSummary: Output.interpolate`Demo workloads are declared in TypeScript and reconciled into namespace ${demoNamespace.name} on ${cluster.cluster.clusterName}.`,
|
||||
};
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-eks-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-eks"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": "../..",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext",
|
||||
"paths": {
|
||||
"alchemy": ["../../packages/alchemy/src/index.ts"],
|
||||
"alchemy/*": ["../../packages/alchemy/src/*"]
|
||||
}
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import JobFunction from "./src/JobFunction.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"JobLambdaHttpApi",
|
||||
{
|
||||
providers: Layer.mergeAll(
|
||||
// Fully configured cloud provider Layers go here:
|
||||
aws,
|
||||
),
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const func = yield* JobFunction;
|
||||
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
|
||||
DashboardBody: func.functionName.pipe(
|
||||
Output.map((functionName) => ({
|
||||
widgets: [
|
||||
{
|
||||
type: "metric",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Invocations and Errors",
|
||||
region: dashboardRegion,
|
||||
stat: "Sum",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Invocations", "FunctionName", functionName],
|
||||
["AWS/Lambda", "Errors", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "metric",
|
||||
x: 12,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Duration",
|
||||
region: dashboardRegion,
|
||||
stat: "Average",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Duration", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
),
|
||||
});
|
||||
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
|
||||
AlarmDescription:
|
||||
"Alerts when the example Lambda function reports errors.",
|
||||
MetricName: "Errors",
|
||||
Namespace: "AWS/Lambda",
|
||||
Statistic: "Sum",
|
||||
Period: 300,
|
||||
EvaluationPeriods: 1,
|
||||
Threshold: 1,
|
||||
ComparisonOperator: "GreaterThanOrEqualToThreshold",
|
||||
TreatMissingData: "notBreaching",
|
||||
Dimensions: [
|
||||
{
|
||||
Name: "FunctionName",
|
||||
Value: func.functionName,
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
url: Output.interpolate`${func.functionUrl}?jobId=foo`,
|
||||
dashboardName: dashboard.dashboardName,
|
||||
alarmName: alarm.alarmName,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-lambda-httpapi",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-lambda-httpapi"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as S from "effect/Schema";
|
||||
|
||||
export type JobId = S.Schema.Type<typeof JobId>;
|
||||
export const JobId = S.String.annotate({
|
||||
description: "The ID of the job",
|
||||
});
|
||||
|
||||
export class Job extends S.Class<Job>("Job")({
|
||||
id: JobId,
|
||||
content: S.String,
|
||||
}) {}
|
||||
|
||||
export const decodeJob = S.decodeEffect(Job);
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import * as HttpApi from "effect/unstable/httpapi/HttpApi";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as HttpApiEndpoint from "effect/unstable/httpapi/HttpApiEndpoint";
|
||||
import * as HttpApiGroup from "effect/unstable/httpapi/HttpApiGroup";
|
||||
import { Job, JobId } from "./Job.ts";
|
||||
import { JobNotifications, NotifyJobError } from "./JobNotifications.ts";
|
||||
import { GetJobError, JobStorage, PutJobError } from "./JobStorage.ts";
|
||||
|
||||
export const getJob = HttpApiEndpoint.get("getJob", "/", {
|
||||
success: Job,
|
||||
query: {
|
||||
jobId: JobId.pipe(Schema.optional),
|
||||
},
|
||||
});
|
||||
|
||||
export const createJob = HttpApiEndpoint.post("createJob", "/", {
|
||||
success: JobId,
|
||||
payload: Schema.Struct({
|
||||
content: Schema.String,
|
||||
}),
|
||||
});
|
||||
|
||||
export const JobApi = HttpApi.make("JobApi").add(
|
||||
HttpApiGroup.make("Jobs").add(getJob, createJob),
|
||||
);
|
||||
|
||||
export const JobApiLive = HttpApiBuilder.layer(JobApi).pipe(
|
||||
Layer.provide(
|
||||
HttpApiBuilder.group(JobApi, "Jobs", (handlers) =>
|
||||
Effect.gen(function* () {
|
||||
const jobService = yield* JobStorage;
|
||||
const notifications = yield* JobNotifications;
|
||||
|
||||
return handlers
|
||||
.handle(
|
||||
"getJob",
|
||||
Effect.fn(function* (req) {
|
||||
if (!req.query.jobId) {
|
||||
return HttpServerResponse.text("Job ID is required", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
const job = yield* jobService.getJob(req.query.jobId).pipe(
|
||||
Effect.catchTag("GetJobError", (error) =>
|
||||
Effect.succeed(
|
||||
HttpServerResponse.text(error.message, {
|
||||
status: 500,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (job instanceof GetJobError) {
|
||||
return HttpServerResponse.text(job.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
if (!job) {
|
||||
return HttpServerResponse.text("Job not found", {
|
||||
status: 404,
|
||||
});
|
||||
}
|
||||
return job!;
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"createJob",
|
||||
Effect.fn(function* (req) {
|
||||
const jobId = crypto.randomUUID();
|
||||
const job = yield* jobService
|
||||
.putJob({
|
||||
id: jobId,
|
||||
content: req.payload.content,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTag("PutJobError", (error) =>
|
||||
Effect.succeed(error),
|
||||
),
|
||||
);
|
||||
if (job instanceof PutJobError) {
|
||||
return HttpServerResponse.text(job.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
const notificationResult = yield* notifications
|
||||
.notifyJobCreated(job)
|
||||
.pipe(
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.succeed(error),
|
||||
),
|
||||
);
|
||||
if (notificationResult instanceof NotifyJobError) {
|
||||
return HttpServerResponse.text(notificationResult.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
return job.id;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Etag from "effect/unstable/http/Etag";
|
||||
import * as HttpPlatform from "effect/unstable/http/HttpPlatform";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import { JobApiLive } from "./JobApi.ts";
|
||||
import { JobNotificationsSNS } from "./JobNotifications.ts";
|
||||
import { JobStorageDynamoDB } from "./JobStorage.ts";
|
||||
|
||||
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
|
||||
"JobFunction",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
url: true,
|
||||
},
|
||||
HttpRouter.toHttpEffect(JobApiLive).pipe(
|
||||
Effect.map((fetch) => ({ fetch })),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
JobStorageDynamoDB,
|
||||
JobNotificationsSNS,
|
||||
// TODO(sam): these should be provided to us automatically
|
||||
HttpPlatform.layer,
|
||||
Etag.layer,
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
type JobNotification = {
|
||||
type: "job.created";
|
||||
job: Job;
|
||||
};
|
||||
|
||||
export class JobNotifications extends Context.Service<
|
||||
JobNotifications,
|
||||
{
|
||||
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
|
||||
}
|
||||
>()("JobNotifications") {}
|
||||
|
||||
export const JobNotificationsSNS = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobNotifications,
|
||||
Effect.gen(function* () {
|
||||
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
|
||||
attributes: {
|
||||
DisplayName: "job-notifications",
|
||||
},
|
||||
});
|
||||
|
||||
const publish = yield* AWS.SNS.Publish.bind(topic);
|
||||
|
||||
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.mapEffect((notification) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(notification.Message) as JobNotification,
|
||||
catch: (cause) =>
|
||||
new NotifyJobError({
|
||||
message: "Failed to parse SNS job notification",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((payload) =>
|
||||
Effect.logInfo(
|
||||
`Job notification received: ${payload.type} (${payload.job.id})`,
|
||||
),
|
||||
),
|
||||
// Keep the example resilient to malformed demo messages.
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.logWarning(error.message),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.runDrain,
|
||||
),
|
||||
);
|
||||
|
||||
const notifyJobCreated = (job: Job) =>
|
||||
publish({
|
||||
Subject: "JobCreated",
|
||||
Message: JSON.stringify({
|
||||
type: "job.created",
|
||||
job,
|
||||
} satisfies JobNotification),
|
||||
}).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NotifyJobError({
|
||||
message: `Failed to publish job notification for "${job.id}"`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return JobNotifications.of({
|
||||
notifyJobCreated,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
|
||||
);
|
||||
@@ -0,0 +1,230 @@
|
||||
import * as DynamoDB from "alchemy/AWS/DynamoDB";
|
||||
import * as Lambda from "alchemy/AWS/Lambda";
|
||||
import * as S3 from "alchemy/AWS/S3";
|
||||
import * as SQS from "alchemy/AWS/SQS";
|
||||
import * as RemovalPolicy from "alchemy/RemovalPolicy";
|
||||
import { Stack } from "alchemy/Stack";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class PutJobError extends Data.TaggedError("PutJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class GetJobError extends Data.TaggedError("GetJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class JobStorage extends Context.Service<
|
||||
JobStorage,
|
||||
{
|
||||
putJob(job: Job): Effect.Effect<Job, PutJobError>;
|
||||
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
|
||||
}
|
||||
>()("JobStorage") {}
|
||||
|
||||
export const JobStorageDynamoDB = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const table = yield* DynamoDB.Table("JobsTable", {
|
||||
partitionKey: "id",
|
||||
attributes: {
|
||||
id: "S",
|
||||
},
|
||||
});
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getItem = yield* DynamoDB.GetItem.bind(table);
|
||||
const putItem = yield* DynamoDB.PutItem.bind(table);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
yield* DynamoDB.stream(table, {
|
||||
streamViewType: "NEW_AND_OLD_IMAGES",
|
||||
startingPosition: "LATEST",
|
||||
batchSize: 10,
|
||||
}).process((stream) =>
|
||||
stream.pipe(
|
||||
Stream.map((record) =>
|
||||
JSON.stringify({
|
||||
eventName: record.eventName,
|
||||
keys: record.dynamodb.Keys,
|
||||
newImage: record.dynamodb.NewImage,
|
||||
oldImage: record.dynamodb.OldImage,
|
||||
}),
|
||||
),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putItem({
|
||||
Item: {
|
||||
id: { S: job.id },
|
||||
content: { S: job.content },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getItem({
|
||||
Key: {
|
||||
id: { S: jobId },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flatMap((item) =>
|
||||
item.Item
|
||||
? Effect.try({
|
||||
try: () =>
|
||||
({
|
||||
id: item.Item?.id?.S ?? jobId,
|
||||
content: item.Item?.content?.S ?? "",
|
||||
}) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
DynamoDB.GetItemLive,
|
||||
DynamoDB.PutItemLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const JobStorageS3 = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const bucket = yield* S3.Bucket("JobsBucket");
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getObject = yield* S3.GetObject.bind(bucket);
|
||||
const putObject = yield* S3.PutObject.bind(bucket);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putObject({
|
||||
Key: job.id,
|
||||
Body: JSON.stringify(job),
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getObject({
|
||||
Key: jobId,
|
||||
}).pipe(
|
||||
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
|
||||
Effect.flatMap(
|
||||
(item) =>
|
||||
item?.Body?.pipe(
|
||||
Stream.decodeText,
|
||||
Stream.mkString,
|
||||
Effect.flatMap((body) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(body) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
) ?? Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* S3.notifications(bucket).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.flatMap((item) =>
|
||||
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
|
||||
),
|
||||
Stream.filter((job): job is Job => job !== undefined),
|
||||
Stream.map((job) => JSON.stringify(job)),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
S3.GetObjectLive,
|
||||
S3.PutObjectLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import JobFunction from "./src/JobFunction.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"JobLambdaRpc",
|
||||
{
|
||||
providers: Layer.mergeAll(
|
||||
// Fully configured cloud provider Layers go here:
|
||||
aws,
|
||||
),
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const func = yield* JobFunction;
|
||||
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
|
||||
DashboardBody: func.functionName.pipe(
|
||||
Output.map((functionName) => ({
|
||||
widgets: [
|
||||
{
|
||||
type: "metric",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Invocations and Errors",
|
||||
region: dashboardRegion,
|
||||
stat: "Sum",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Invocations", "FunctionName", functionName],
|
||||
["AWS/Lambda", "Errors", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "metric",
|
||||
x: 12,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Duration",
|
||||
region: dashboardRegion,
|
||||
stat: "Average",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Duration", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
),
|
||||
});
|
||||
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
|
||||
AlarmDescription:
|
||||
"Alerts when the example Lambda function reports errors.",
|
||||
MetricName: "Errors",
|
||||
Namespace: "AWS/Lambda",
|
||||
Statistic: "Sum",
|
||||
Period: 300,
|
||||
EvaluationPeriods: 1,
|
||||
Threshold: 1,
|
||||
ComparisonOperator: "GreaterThanOrEqualToThreshold",
|
||||
TreatMissingData: "notBreaching",
|
||||
Dimensions: [
|
||||
{
|
||||
Name: "FunctionName",
|
||||
Value: func.functionName,
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
url: func.functionUrl,
|
||||
dashboardName: dashboard.dashboardName,
|
||||
alarmName: alarm.alarmName,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-lambda-rpc",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-lambda-rpc"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as S from "effect/Schema";
|
||||
|
||||
export type JobId = S.Schema.Type<typeof JobId>;
|
||||
export const JobId = S.String.annotate({
|
||||
description: "The ID of the job",
|
||||
});
|
||||
|
||||
export class Job extends S.Class<Job>("Job")({
|
||||
id: JobId,
|
||||
content: S.String,
|
||||
}) {}
|
||||
|
||||
export const decodeJob = S.decodeEffect(Job);
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { JobNotificationsSNS } from "./JobNotifications.ts";
|
||||
import { JobRpcHttpEffect } from "./JobRpcApi.ts";
|
||||
import { JobStorageDynamoDB } from "./JobStorage.ts";
|
||||
|
||||
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
|
||||
"JobFunction",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
url: true,
|
||||
},
|
||||
JobRpcHttpEffect.pipe(
|
||||
Effect.map((fetch) => ({ fetch })),
|
||||
Effect.provide(Layer.mergeAll(JobStorageDynamoDB, JobNotificationsSNS)),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
type JobNotification = {
|
||||
type: "job.created";
|
||||
job: Job;
|
||||
};
|
||||
|
||||
export class JobNotifications extends Context.Service<
|
||||
JobNotifications,
|
||||
{
|
||||
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
|
||||
}
|
||||
>()("JobNotifications") {}
|
||||
|
||||
export const JobNotificationsSNS = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobNotifications,
|
||||
Effect.gen(function* () {
|
||||
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
|
||||
attributes: {
|
||||
DisplayName: "job-notifications",
|
||||
},
|
||||
});
|
||||
|
||||
const publish = yield* AWS.SNS.Publish.bind(topic);
|
||||
|
||||
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.mapEffect((notification) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(notification.Message) as JobNotification,
|
||||
catch: (cause) =>
|
||||
new NotifyJobError({
|
||||
message: "Failed to parse SNS job notification",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((payload) =>
|
||||
Effect.logInfo(
|
||||
`Job notification received: ${payload.type} (${payload.job.id})`,
|
||||
),
|
||||
),
|
||||
// Keep the example resilient to malformed demo messages.
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.logWarning(error.message),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.runDrain,
|
||||
),
|
||||
);
|
||||
|
||||
const notifyJobCreated = (job: Job) =>
|
||||
publish({
|
||||
Subject: "JobCreated",
|
||||
Message: JSON.stringify({
|
||||
type: "job.created",
|
||||
job,
|
||||
} satisfies JobNotification),
|
||||
}).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NotifyJobError({
|
||||
message: `Failed to publish job notification for "${job.id}"`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return JobNotifications.of({
|
||||
notifyJobCreated,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
|
||||
);
|
||||
Loaded 100 of 6105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user