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 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
import asyncio
import json
import sqlite3
import threading
import traceback
import uuid
from contextlib import closing
from typing import Literal

import pytest
import pytest_asyncio

from free_claude_code.application.code_sessions.models import (
    CodeConflictError,
    CodeItem,
    CodePrompt,
    CodeRun,
    CodeSession,
    CodeUnavailableError,
)
from free_claude_code.runtime import code_sessions_sqlite as code_store_module
from free_claude_code.runtime.code_sessions_sqlite import SQLiteCodeStore
from free_claude_code.runtime.sqlite_database import SQLiteDatabase


@pytest.mark.asyncio
async def test_failed_history_decode_cannot_leak_snapshot_to_next_reader(store):
    session = await store.create(
        CodeSession(id="s", cwd="/work", model="provider/model", title="before")
    )

    def seed(connection):
        for index in range(2):
            code_store_module._insert(
                connection,
                "code_runs",
                CodeRun(
                    id=f"r{index}",
                    session_id=session.id,
                    text="test",
                    model=session.model,
                    ordinal=index + 1,
                    status="completed",
                ),
            )
        connection.execute(
            "UPDATE code_runs SET error_details='invalid json' WHERE id='r0'"
        ).close()

    await store.database.run(seed)
    with pytest.raises(json.JSONDecodeError) as failure:
        await store.runs(session.id)
    # Keep the traceback, and therefore its unfinished SELECT cursor, alive.
    try:
        await store.database.run(
            lambda connection: connection.execute(
                "UPDATE code_sessions SET title='after' WHERE id=?", (session.id,)
            ).close()
        )
        with closing(sqlite3.connect(store.database.path)) as external:
            assert (
                external.execute(
                    "SELECT title FROM code_sessions WHERE id=?", (session.id,)
                ).fetchone()[0]
                == "after"
            )
        assert (await store.get_session(session.id)).title == "after"
    finally:
        traceback.clear_frames(failure.value.__traceback__)


@pytest.mark.asyncio
async def test_cancelled_initialization_drains_thread_before_releasing_owner_lock(
    database_factory,
    tmp_path,
):
    entered = threading.Event()
    release = threading.Event()
    initialized = threading.Event()

    class GatedDatabase(SQLiteDatabase):
        def _initialize(self):
            entered.set()
            assert release.wait(5)
            super()._initialize()
            initialized.set()

    store = SQLiteCodeStore(GatedDatabase(tmp_path / "code.db", tmp_path / "code.lock"))
    starting = asyncio.create_task(store.start())
    await asyncio.to_thread(entered.wait, 3)
    starting.cancel()
    release.set()
    with pytest.raises(asyncio.CancelledError):
        await starting
    await asyncio.to_thread(initialized.wait, 3)
    second = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    try:
        await second.start()
        session = await second.create(
            CodeSession(id=str(uuid.uuid4()), cwd=str(tmp_path), model="provider/model")
        )
        assert (await second.get_session(session.id)).id == session.id
    finally:
        await store.close()
        await store.database.close()
        await second.close()
        await second.database.close()


@pytest.mark.asyncio
async def test_store_has_one_process_owner_and_can_reopen_after_close(
    database_factory, tmp_path
):
    first = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    second = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    await first.start()
    try:
        with pytest.raises(CodeUnavailableError, match="another FCC"):
            await second.start()
    finally:
        await first.close()
        await first.database.close()
    second = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    await second.start()
    await second.close()
    await second.database.close()


@pytest.mark.asyncio
async def test_reused_item_id_cannot_overwrite_another_session(
    database_factory, tmp_path
):
    store = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    await store.start()
    try:
        first, second = [
            await store.create(
                CodeSession(
                    id=str(uuid.uuid4()), cwd=str(tmp_path), model="provider/model"
                )
            )
            for _ in range(2)
        ]
        shared_id = str(uuid.uuid4())
        first, first_run = await _admit(store, first, text="first")
        original = CodeItem(
            id=shared_id,
            session_id=first.id,
            sequence=2,
            run_id=first_run.id,
            kind="tool",
            text="original output",
            complete=True,
        )
        await store.save_progress(first, first.revision, items=(original,))
        await _admit(store, second, run_id=shared_id, text="second")
        assert (await store.items(first.id, None, None))[-1] == original
        assert (await store.items(second.id, None, None))[0].text == "second"
    finally:
        await store.close()
        await store.database.close()


async def _admit(store, session, *, run_id=None, text="message", sequence=1):
    run_id = run_id or str(uuid.uuid4())
    run = CodeRun(id=run_id, session_id=session.id, text=text, model=session.model)
    item = CodeItem(
        id=run_id,
        session_id=session.id,
        run_id=run_id,
        sequence=sequence,
        kind="user",
        text=text,
        complete=True,
    )
    return await store.admit_run(
        session.model_copy(update={"revision": session.revision + 1}),
        run,
        item,
        session.revision,
    )


@pytest_asyncio.fixture
async def store(database_factory, tmp_path):
    result = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    await result.start()
    yield result
    await result.close()
    await result.database.close()


async def _session(store):
    return await store.create(
        CodeSession(id=str(uuid.uuid4()), cwd="/work", model="provider/model")
    )


@pytest.mark.asyncio
async def test_closed_database_uses_code_storage_error(store):
    await store.database.close()
    with pytest.raises(CodeUnavailableError, match="storage is unavailable") as error:
        await store.get_session("missing")
    assert isinstance(error.value.__cause__, sqlite3.OperationalError)


@pytest.mark.asyncio
async def test_code_read_uses_explicit_connection_policy(store, monkeypatch):
    session = await _session(store)
    read_session = code_store_module._session

    def observe(connection, session_id):
        assert connection.autocommit is True
        assert connection.in_transaction
        assert connection.execute("PRAGMA foreign_keys").fetchone()[0] == 1
        assert connection.execute("SELECT 1 AS value").fetchone()["value"] == 1
        return read_session(connection, session_id)

    monkeypatch.setattr(code_store_module, "_session", observe)
    assert await store.get_session(session.id) == session


@pytest.mark.asyncio
async def test_code_reads_do_not_reserve_writer_while_wal_write_is_open(store):
    session = await _session(store)
    with closing(sqlite3.connect(store.database.path, autocommit=True)) as writer:
        writer.execute("BEGIN IMMEDIATE")
        try:
            writer.execute(
                "UPDATE code_sessions SET title = 'uncommitted' WHERE id = ?",
                (session.id,),
            )
            saved = await asyncio.wait_for(store.get_session(session.id), 3)
            history = await asyncio.wait_for(
                store.read_history(session.id, None, ()), 3
            )
            assert saved == history.session == session
        finally:
            writer.execute("ROLLBACK")


@pytest.mark.asyncio
async def test_recovery_rolls_back_runs_when_prompt_expiration_fails(store):
    session, run = await _admit(store, await _session(store))
    prompt = CodePrompt(
        id="prompt",
        session_id=session.id,
        generation="g",
        request_id=1,
        kind="question",
        form={},
        raw={},
    )
    item = CodeItem(
        id=prompt.id,
        session_id=session.id,
        run_id=run.id,
        sequence=2,
        kind="prompt",
        complete=True,
    )
    await store.save_progress(
        session, session.revision, items=(item,), prompts=(prompt,)
    )
    await store.close()
    await store.database.run(
        lambda connection: connection.execute(
            "CREATE TRIGGER reject_expiration BEFORE UPDATE ON code_prompts "
            "BEGIN SELECT RAISE(ABORT, 'recovery failure'); END"
        )
    )
    try:
        with pytest.raises(CodeConflictError) as error:
            await store.start()
        assert isinstance(error.value.__cause__, sqlite3.IntegrityError)
        states = await store.database.run(
            lambda connection: (
                connection.execute("SELECT status FROM code_runs").fetchone()[0],
                connection.execute("SELECT status FROM code_prompts").fetchone()[0],
            ),
            write=False,
        )
        assert states == (run.status, prompt.status)
    finally:
        await store.database.run(
            lambda connection: connection.execute("DROP TRIGGER reject_expiration")
        )
    await store.start()
    assert (await store.get_run(session.id, run.id)).status == "interrupted"
    assert (await store.get_prompt(session.id, prompt.id)).status == "expired"


@pytest.mark.asyncio
@pytest.mark.parametrize("fail", [False, True])
async def test_cancelled_code_write_delivers_outcome_before_database_close(
    store, database_factory, monkeypatch, tmp_path, fail
):
    entered, release = threading.Event(), threading.Event()
    closing_started = asyncio.Event()
    insert = code_store_module._insert
    session = CodeSession(id="new", cwd="/work", model="provider/model")

    def blocked(connection, table, record):
        insert(connection, table, record)
        entered.set()
        assert release.wait(5)
        if fail:
            raise sqlite3.OperationalError("injected write failure")

    async def close_database():
        closing_started.set()
        await store.database.close()

    monkeypatch.setattr(code_store_module, "_insert", blocked)
    writing = asyncio.create_task(store.create(session))
    closing_task = None
    try:
        assert await asyncio.to_thread(entered.wait, 3)
        writing.cancel()
        closing_task = asyncio.create_task(close_database())
        await asyncio.wait_for(closing_started.wait(), 3)
        assert not closing_task.done()
        with pytest.raises(CodeUnavailableError):
            await store.get_session(session.id)
        other = database_factory(store.database.path, tmp_path / "code.lock")
        with pytest.raises(sqlite3.OperationalError, match="another FCC"):
            await other.start()
        release.set()
        if fail:
            with pytest.raises(CodeUnavailableError) as error:
                await writing
            assert isinstance(error.value.__cause__, sqlite3.OperationalError)
        else:
            assert await writing == session
        await asyncio.wait_for(closing_task, 3)
        reopened = database_factory(store.database.path, tmp_path / "code.lock")
        await reopened.start()
        saved = await reopened.run(
            lambda connection: connection.execute(
                "SELECT id FROM code_sessions"
            ).fetchall(),
            write=False,
        )
        assert [row["id"] for row in saved] == ([] if fail else [session.id])
    finally:
        release.set()
        await asyncio.gather(
            writing, *([closing_task] if closing_task else []), return_exceptions=True
        )


@pytest.mark.asyncio
async def test_history_snapshot_decodes_only_selected_records_and_chunks_includes(
    store, monkeypatch
):
    session, run = await _admit(store, await _session(store))
    items = tuple(
        CodeItem(
            id=str(uuid.uuid4()),
            session_id=session.id,
            run_id=run.id,
            sequence=number,
            kind="text",
            text=str(number),
            complete=True,
        )
        for number in range(2, 1203)
    )
    await store.save_progress(
        session,
        session.revision,
        items=items,
        run=run.model_copy(update={"status": "completed"}),
    )
    for number in range(1203, 1243):
        session, later = await _admit(store, session, sequence=number)
        await store.save_progress(
            session,
            session.revision,
            run=later.model_copy(update={"status": "completed"}),
        )
    decoded = []
    record = code_store_module._record

    def observe(model, row):
        decoded.append(model)
        return record(model, row)

    monkeypatch.setattr(code_store_module, "_record", observe)
    first = await store.read_history(session.id, None, ())
    assert len(first.items) == 50
    assert decoded.count(CodeItem) == 50
    assert decoded.count(CodeRun) <= 2 * len(first.runs) + 1
    decoded.clear()
    seed = await store.execution_seed(session.id)
    assert seed.sequence == 1242 and not seed.items and not seed.prompts
    assert len(seed.runs) == 1 and decoded.count(CodeRun) == 2
    included = await store.read_history(session.id, None, [item.id for item in items])
    assert {item.id for item in items} <= {item.id for item in included.items}
    assert len({item.id for item in included.items}) == len(included.items)


@pytest.mark.asyncio
async def test_history_component_reads_share_one_sqlite_snapshot(store, monkeypatch):
    session, run = await _admit(store, await _session(store))
    await store.save_progress(
        session, session.revision, run=run.model_copy(update={"status": "completed"})
    )
    page = code_store_module._item_page

    def change_after_page(connection, session_id, before, limit):
        result = page(connection, session_id, before, limit)
        with closing(sqlite3.connect(store.database.path)) as writer, writer:
            writer.execute(
                "UPDATE code_sessions SET title = 'new' WHERE id = ?", (session.id,)
            )
            writer.execute(
                "UPDATE code_items SET text = 'changed' WHERE session_id = ?",
                (session.id,),
            )
        return result

    monkeypatch.setattr(code_store_module, "_item_page", change_after_page)
    detail = await store.read_history(session.id, None, (run.id,))
    assert detail.session.title == session.title
    assert detail.items[0].text == "message"
    assert (await store.get_session(session.id)).title == "new"
    assert (await store.run_items(session.id, run.id))[0].text == "changed"


@pytest.mark.asyncio
async def test_active_prompt_and_identity_queries_have_indexed_access(store):
    with closing(sqlite3.connect(store.database.path)) as connection:
        queries = (
            (
                "SELECT * FROM code_prompts WHERE session_id = ? AND status IN ('pending', 'answering')",
                ("session",),
            ),
            ("SELECT max(sequence) FROM code_items WHERE session_id = ?", ("session",)),
            (
                "SELECT * FROM code_items WHERE session_id = ? AND native_turn_id = ? AND native_item_id = ?",
                ("session", "turn", "item"),
            ),
        )
        for query, params in queries:
            details = [
                row[3].upper()
                for row in connection.execute("EXPLAIN QUERY PLAN " + query, params)
            ]
            assert any("SEARCH" in detail and "INDEX" in detail for detail in details)


@pytest.mark.asyncio
async def test_mode_and_original_defaults_survive_restart_and_cannot_be_rewritten(
    store, tmp_path
):
    session = await _session(store)
    with closing(sqlite3.connect(tmp_path / "code.db")) as connection:
        assert connection.execute(
            "SELECT native_permission_defaults FROM code_sessions"
        ).fetchone() == (None,)
    defaults = {
        "approvalPolicy": "on-request",
        "approvalsReviewer": "user",
        "sandbox": {"type": "readOnly"},
    }
    session = session.model_copy(update={"native_permission_defaults": defaults})
    await store.save_progress(session, session.revision)
    for replacement in (None, {"different": True}):
        with pytest.raises(CodeConflictError):
            await store.save_progress(
                session.model_copy(update={"native_permission_defaults": replacement}),
                session.revision,
            )
    session = await store.update_settings(
        session.model_copy(
            update={"mode": "full_access", "revision": session.revision + 1}
        ),
        session.revision,
    )
    await store.close()
    await store.start()
    saved = await store.get_session(session.id)
    assert saved.mode == "full_access"
    assert saved.native_permission_defaults == defaults


@pytest.mark.asyncio
async def test_context_usage_progress_and_settings_use_existing_session_writes(
    store,
):
    session = await _session(store)
    snapshot = session.model_copy(update={"context_used_tokens": 12_438})
    await store.save_progress(snapshot, session.revision)
    saved = await store.get_session(session.id)
    assert saved.context_used_tokens == 12_438
    assert saved.revision == session.revision
    assert saved.updated_at == session.updated_at

    changed = snapshot.model_copy(
        update={
            "model": "provider/other",
            "revision": snapshot.revision + 1,
        }
    )
    changed = await store.update_settings(changed, snapshot.revision)
    assert changed.model == "provider/other"
    assert changed.context_used_tokens == 12_438


@pytest.mark.asyncio
async def test_mode_is_guarded_by_sqlite_busy_and_run_immutability(store):
    session, run = await _admit(store, await _session(store))
    with pytest.raises(CodeConflictError):
        await store.update_settings(
            session.model_copy(
                update={"mode": "full_access", "revision": session.revision + 1}
            ),
            session.revision,
        )
    with pytest.raises(CodeConflictError):
        await store.save_progress(
            session,
            session.revision,
            run=run.model_copy(update={"mode": "full_access"}),
        )


@pytest.mark.asyncio
async def test_version_one_database_gains_mode_without_losing_history(
    database_factory, store, tmp_path
):
    session, run = await _admit(store, await _session(store))
    items = await store.items(session.id, None, None)
    await store.close()
    await store.database.close()
    with closing(sqlite3.connect(tmp_path / "code.db")) as connection, connection:
        connection.execute("ALTER TABLE code_sessions DROP COLUMN mode")
        connection.execute(
            "ALTER TABLE code_sessions DROP COLUMN native_permission_defaults"
        )
        connection.execute("ALTER TABLE code_sessions DROP COLUMN context_used_tokens")
        connection.execute("ALTER TABLE code_runs DROP COLUMN mode")
        connection.execute("DROP INDEX code_prompts_active")
        drop_messaging_schema(connection)
        connection.execute("PRAGMA user_version = 1")
    for _ in range(2):
        store = SQLiteCodeStore(
            database_factory(tmp_path / "code.db", tmp_path / "code.lock")
        )
        await store.start()
        saved = await store.get_session(session.id)
        assert saved.mode == "config"
        assert saved.native_permission_defaults is None
        saved_run = await store.get_run(session.id, run.id)
        assert saved_run is not None and saved_run.mode == "config"
        assert await store.items(session.id, None, None) == items
        with closing(sqlite3.connect(tmp_path / "code.db")) as connection:
            assert connection.execute("PRAGMA user_version").fetchone()[0] == 5
            with pytest.raises(sqlite3.IntegrityError):
                connection.execute("UPDATE code_sessions SET mode = 'unknown'")
            with pytest.raises(sqlite3.IntegrityError):
                connection.execute(
                    "UPDATE code_sessions SET native_permission_defaults = '[]'"
                )
        await store.close()
        await store.database.close()


@pytest.mark.asyncio
async def test_version_two_database_gains_nullable_context_usage(
    database_factory, store, tmp_path
):
    session = await _session(store)
    await store.close()
    await store.database.close()
    with closing(sqlite3.connect(tmp_path / "code.db")) as connection, connection:
        connection.execute("ALTER TABLE code_sessions DROP COLUMN context_used_tokens")
        connection.execute("DROP INDEX code_prompts_active")
        drop_messaging_schema(connection)
        connection.execute("PRAGMA user_version = 2")
    for _ in range(2):
        store = SQLiteCodeStore(
            database_factory(tmp_path / "code.db", tmp_path / "code.lock")
        )
        await store.start()
        assert (await store.get_session(session.id)).context_used_tokens is None
        with closing(sqlite3.connect(tmp_path / "code.db")) as connection:
            assert connection.execute("PRAGMA user_version").fetchone()[0] == 5
            column = next(
                row
                for row in connection.execute("PRAGMA table_info(code_sessions)")
                if row[1] == "context_used_tokens"
            )
            assert column[3] == 0
            with pytest.raises(sqlite3.IntegrityError):
                connection.execute(
                    "UPDATE code_sessions SET context_used_tokens = -1 WHERE id = ?",
                    (session.id,),
                )
        await store.close()
        await store.database.close()


@pytest.mark.asyncio
async def test_admission_is_atomic_and_idempotent(store):
    session = await _session(store)
    results = await asyncio.gather(
        _admit(store, session), _admit(store, session), return_exceptions=True
    )
    assert sum(isinstance(result, CodeConflictError) for result in results) == 1
    session, run = next(result for result in results if isinstance(result, tuple))
    assert (
        len(await store.runs(session.id))
        == len(await store.items(session.id, None, None))
        == 1
    )
    assert await _admit(store, session, run_id=run.id) == (session, run)
    await store.save_progress(
        session, session.revision, run=run.model_copy(update={"status": "completed"})
    )
    collision = CodeItem(
        id=str(uuid.uuid4()),
        session_id=session.id,
        run_id=run.id,
        sequence=2,
        kind="tool",
        text="keep me",
        complete=True,
    )
    await store.save_progress(session, session.revision, items=(collision,))
    with pytest.raises(CodeConflictError):
        await _admit(store, session, run_id=collision.id, sequence=3)
    assert (await store.get_session(session.id)).revision == session.revision
    assert len(await store.runs(session.id)) == 1
    assert (await store.items(session.id, None, None))[-1] == collision


@pytest.mark.asyncio
async def test_schema_rejects_second_active_run_and_cross_session_item_link(
    store, tmp_path
):
    session, run = await _admit(store, await _session(store))
    other = await _session(store)
    with closing(sqlite3.connect(tmp_path / "code.db")) as connection:
        connection.execute("PRAGMA foreign_keys = ON")
        columns = [row[1] for row in connection.execute("PRAGMA table_info(code_runs)")]
        expressions = [
            "'another'"
            if column == "id"
            else "ordinal + 1"
            if column == "ordinal"
            else column
            for column in columns
        ]
        with pytest.raises(sqlite3.IntegrityError):
            connection.execute(
                f"INSERT INTO code_runs SELECT {','.join(expressions)} FROM code_runs"
            )
        columns = [
            row[1] for row in connection.execute("PRAGMA table_info(code_items)")
        ]
        expressions = ["?" if column == "session_id" else column for column in columns]
        with pytest.raises(sqlite3.IntegrityError):
            connection.execute(
                f"INSERT INTO code_items SELECT {','.join(expressions)} FROM code_items",
                (other.id,),
            )
    assert await store.get_run(session.id, run.id) == run


@pytest.mark.asyncio
async def test_prompt_claim_and_settings_are_guarded_in_storage(store):
    session, run = await _admit(store, await _session(store))
    await store.save_progress(
        session, session.revision, run=run.model_copy(update={"status": "completed"})
    )
    prompts = tuple(
        CodePrompt(
            id=str(uuid.uuid4()),
            session_id=session.id,
            generation="g",
            request_id=request_id,
            kind="question",
            form={},
            raw={},
        )
        for request_id in (1, "1")
    )
    items = tuple(
        CodeItem(
            id=prompt.id,
            session_id=session.id,
            run_id=run.id,
            sequence=index + 2,
            kind="prompt",
            complete=True,
        )
        for index, prompt in enumerate(prompts)
    )
    await store.save_progress(session, session.revision, items=items, prompts=prompts)
    results = await asyncio.gather(
        *(
            store.claim_prompt(session.id, prompts[0].id, str(uuid.uuid4()), "g")
            for _ in range(2)
        ),
        return_exceptions=True,
    )
    assert sum(isinstance(result, CodeConflictError) for result in results) == 1
    claimed = next(result for result in results if isinstance(result, CodePrompt))
    assert (
        await store.claim_prompt(session.id, claimed.id, claimed.response_id, "g")
        == claimed
    )
    with pytest.raises(CodeConflictError):
        await store.claim_prompt(session.id, prompts[1].id, claimed.response_id, "g")
    settings = session.model_copy(
        update={"model": "provider/other", "revision": session.revision + 1}
    )
    with pytest.raises(CodeConflictError):
        await store.update_settings(settings, session.revision)
    await store.save_progress(
        session,
        session.revision,
        prompts=(
            claimed.model_copy(update={"status": "resolved"}),
            prompts[1].model_copy(update={"status": "expired"}),
        ),
    )
    assert (
        await store.update_settings(settings, session.revision)
    ).model == "provider/other"
    with pytest.raises(CodeConflictError):
        await store.update_settings(
            session.model_copy(update={"title": "stale"}), session.revision
        )


@pytest.mark.asyncio
async def test_recovered_old_output_pages_with_its_original_run_outcome(store):
    session, old = await _admit(store, await _session(store))
    old = old.model_copy(update={"status": "failed", "error": "first failed"})
    await store.save_progress(session, session.revision, run=old)
    session, newer = await _admit(store, session, sequence=2)
    tail = CodeItem(
        id=str(uuid.uuid4()),
        session_id=session.id,
        run_id=old.id,
        sequence=3,
        kind="assistant",
        text="recovered",
        complete=True,
    )
    await store.save_progress(session, session.revision, items=(tail,))
    page = await store.item_page(session.id, None, 2)
    assert [item.run_id for item in page.items] == [old.id, newer.id]
    assert page.runs[0].error == "first failed"
    assert page.next_before == (old.ordinal, 3)
    older = await store.item_page(session.id, page.next_before, 2)
    assert [item.sequence for item in older.items] == [1]


@pytest.mark.asyncio
async def test_prompt_entry_and_form_are_atomic_and_linked_in_storage(store, tmp_path):
    session, run = await _admit(store, await _session(store))
    prompt = CodePrompt(
        id=str(uuid.uuid4()),
        session_id=session.id,
        generation="g",
        request_id=1,
        kind="questions",
        form={},
        raw={},
    )
    item = CodeItem(
        id=prompt.id,
        session_id=session.id,
        run_id=run.id,
        sequence=2,
        kind="prompt",
        complete=True,
    )
    with pytest.raises(CodeConflictError):
        await store.save_progress(session, session.revision, prompts=(prompt,))
    with pytest.raises(CodeConflictError):
        await store.save_progress(
            session,
            session.revision,
            items=(item.model_copy(update={"kind": "text"}),),
            prompts=(prompt,),
        )
    assert await store.prompts(session.id) == ()
    assert len(await store.items(session.id, None, None)) == 1
    await store.save_progress(
        session, session.revision, items=(item,), prompts=(prompt,)
    )
    other = await _session(store)
    with closing(sqlite3.connect(tmp_path / "code.db")) as connection:
        connection.execute("PRAGMA foreign_keys = ON")
        with pytest.raises(sqlite3.IntegrityError):
            connection.execute("UPDATE code_prompts SET session_id = ?", (other.id,))
        connection.rollback()
        with pytest.raises(sqlite3.IntegrityError):
            connection.execute("UPDATE code_prompts SET id = 'unlinked'")
    assert await store.prompts(session.id) == (prompt,)


_LEGACY_PROMPTS = """
CREATE TABLE code_prompts(
    session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE,
    id TEXT NOT NULL, generation TEXT NOT NULL, request_id TEXT NOT NULL,
    native_turn_id TEXT, native_item_id TEXT, kind TEXT NOT NULL,
    form TEXT NOT NULL, raw TEXT NOT NULL,
    status TEXT NOT NULL CHECK(status IN ('pending','answering','resolved','expired')),
    response_id TEXT, error TEXT,
    PRIMARY KEY(session_id,id), UNIQUE(session_id,generation,request_id),
    UNIQUE(session_id,response_id)
)
"""


async def _legacy_prompt_database(store, path):
    session, old = await _admit(store, await _session(store))
    await store.save_progress(
        session,
        session.revision,
        run=old.model_copy(
            update={
                "native_turn_id": "old-turn",
                "submission_started": True,
                "status": "completed",
            }
        ),
    )
    tool = CodeItem(
        id=str(uuid.uuid4()),
        session_id=session.id,
        run_id=old.id,
        sequence=2,
        native_turn_id="old-turn",
        native_item_id="shared-tool",
        kind="tool",
        text="Original tool output",
        complete=True,
    )
    await store.save_progress(session, session.revision, items=(tool,))
    session, latest = await _admit(store, session, text="Later turn", sequence=3)
    await store.save_progress(
        session,
        session.revision,
        run=latest.model_copy(
            update={
                "status": "completed",
            }
        ),
    )
    original = await store.items(session.id, None, None)
    await store.close()
    await store.database.close()
    cases: list[
        tuple[str | None, str | None, Literal["resolved", "expired", "pending"]]
    ] = [
        ("old-turn", None, "resolved"),
        (None, "shared-tool", "expired"),
        (None, None, "resolved"),
        ("missing-turn", None, "pending"),
        ("old-turn", None, "expired"),
    ]
    prompts = tuple(
        CodePrompt(
            id=str(uuid.uuid4()),
            session_id=session.id,
            generation="g",
            request_id=index,
            native_turn_id=turn,
            native_item_id=item,
            kind="questions",
            form={"title": "Old question"},
            raw={"keep": "native payload"},
            status=status,
            response_id=str(uuid.uuid4()) if status == "resolved" else None,
        )
        for index, (turn, item, status) in enumerate(cases)
    )
    with closing(sqlite3.connect(path)) as connection, connection:
        connection.execute("DROP TABLE code_prompts")
        connection.execute(_LEGACY_PROMPTS)
        connection.execute("ALTER TABLE code_sessions DROP COLUMN mode")
        connection.execute(
            "ALTER TABLE code_sessions DROP COLUMN native_permission_defaults"
        )
        connection.execute("ALTER TABLE code_sessions DROP COLUMN context_used_tokens")
        connection.execute("ALTER TABLE code_runs DROP COLUMN mode")
        drop_messaging_schema(connection)
        connection.execute("PRAGMA user_version = 0")
        for prompt in prompts:
            connection.execute(
                "INSERT INTO code_prompts VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
                (
                    session.id,
                    prompt.id,
                    prompt.generation,
                    json.dumps(prompt.request_id),
                    prompt.native_turn_id,
                    prompt.native_item_id,
                    prompt.kind,
                    json.dumps(prompt.form),
                    json.dumps(prompt.raw),
                    prompt.status,
                    prompt.response_id,
                    prompt.error,
                ),
            )
    return session, old, latest, original, prompts


@pytest.mark.asyncio
async def test_legacy_prompts_migrate_once_to_run_ends_without_resequencing(
    database_factory, store, tmp_path
):
    path = tmp_path / "code.db"
    session, old, latest, original, prompts = await _legacy_prompt_database(store, path)
    for _ in range(2):
        store = SQLiteCodeStore(
            database_factory(tmp_path / "code.db", tmp_path / "code.lock")
        )
        await store.start()
        items = await store.items(session.id, None, None)
        assert [item.id for item in items] == [
            original[0].id,
            original[1].id,
            prompts[0].id,
            prompts[1].id,
            prompts[4].id,
            original[2].id,
            prompts[2].id,
            prompts[3].id,
        ]
        assert [item for item in items if item.kind != "prompt"] == list(original)
        entries = {item.id: item for item in items if item.kind == "prompt"}
        for index, prompt in enumerate(prompts):
            entry = entries[prompt.id]
            assert entry.run_id == (old.id if index in (0, 1, 4) else latest.id)
            assert entry.sequence == len(original) + index + 1
            assert entry.native_item_id is None and entry.native_turn_id is None
            assert entry.raw == {} and entry.text == ""
        saved = {prompt.id: prompt for prompt in await store.prompts(session.id)}
        for prompt in prompts:
            expected = (
                prompt.model_copy(update={"status": "expired"})
                if prompt.status == "pending"
                else prompt
            )
            assert saved[prompt.id] == expected
        with closing(sqlite3.connect(path)) as connection:
            assert connection.execute("PRAGMA user_version").fetchone()[0] == 5
            assert connection.execute("PRAGMA foreign_key_check").fetchall() == []
            assert any(
                row[2] == "code_items"
                for row in connection.execute("PRAGMA foreign_key_list(code_prompts)")
            )
        await store.close()
        await store.database.close()


@pytest.mark.asyncio
async def test_failed_prompt_migration_rolls_back_items_schema_and_version(
    database_factory, store, tmp_path
):
    path = tmp_path / "code.db"
    _, _, _, original, prompts = await _legacy_prompt_database(store, path)
    with closing(sqlite3.connect(path)) as connection, connection:
        connection.execute(
            "CREATE TRIGGER refuse_second_prompt BEFORE INSERT ON code_items "
            "WHEN NEW.id = '"
            + prompts[1].id
            + "' BEGIN SELECT RAISE(ABORT, 'blocked'); END"
        )
    with pytest.raises(CodeConflictError):
        store = SQLiteCodeStore(
            database_factory(tmp_path / "code.db", tmp_path / "code.lock")
        )
        await store.start()
    with closing(sqlite3.connect(path)) as connection, connection:
        assert connection.execute("PRAGMA user_version").fetchone()[0] == 0
        assert connection.execute("SELECT count(*) FROM code_items").fetchone()[
            0
        ] == len(original)
        assert connection.execute("SELECT count(*) FROM code_prompts").fetchone()[
            0
        ] == len(prompts)
        assert not any(
            row[2] == "code_items"
            for row in connection.execute("PRAGMA foreign_key_list(code_prompts)")
        )
        connection.execute("DROP TRIGGER refuse_second_prompt")
    store = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    await store.start()
    assert len(await store.items(prompts[0].session_id, None, None)) == len(
        original
    ) + len(prompts)


def drop_messaging_schema(connection):
    for table in (
        "messaging_references",
        "messaging_nodes",
        "messaging_trees",
        "messaging_managed_messages",
        "messaging_legacy_import",
    ):
        connection.execute(f"DROP TABLE {table}")