Repository navigation
Expand file tree
/
Copy pathtest_handoff_runtime.py
More file actions
735 lines (660 loc) · 32.1 KB
/
Copy pathtest_handoff_runtime.py
File metadata and controls
735 lines (660 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# Copyright (c) 2026 OceanBase.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import asyncio
import json
from datetime import UTC, datetime
from pathlib import Path
import pytest
import time_machine
from powercontext.artifacts import ArtifactRef
from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent
from powercontext.builtin.artifacts.handoff import (
HandoffEvidenceUnavailableError,
HandoffScopeMismatchError,
PrepareHandoff,
PrepareHandoffHint,
)
from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile
from powercontext.builtin.persistence.tables import BUILTIN_TABLES
from powercontext.builtin.records import ArtifactWrite
from powercontext.builtin.runtime import (
ActivateHandoff,
BuiltinConfig,
CaptureSource,
CaptureWorkingNote,
HandoffArtifactCitation,
HandoffDraft,
HandoffOmission,
HandoffSourceCitation,
HandoffStatement,
InferenceConfig,
PreparedHandoff,
WorkingNoteKind,
open_builtin_runtime,
)
from powercontext.builtin.runtime.relational import RelationalContexts
from powercontext.builtin.scope import ScopeDraft
from powercontext.builtin.source_eligibility import SourceNotEligibleError, WorkingNoteUnavailableError
from powercontext.errors import RevisionConflictError
from powercontext.sources import SourceDefinitionRegistry, SourceRef
from tests.builtin.persistence.contract import SOURCE_ADAPTERS, CommitAdapter, CommitInput, NoteInput
class _EchoHandoffPipeline:
async def generate(self, request, /) -> HandoffDraft:
citation = request.evidence[0].citation
return HandoffDraft(
objective=request.objective,
state=(
HandoffStatement(
text="The parser maps malformed input to a stable public error.",
citations=(citation,),
),
),
disposition="continuable",
next_action=HandoffStatement(
text="Run public-interface regression tests.",
citations=(citation,),
),
)
def test_handoff_can_use_an_explicit_working_note_citation() -> None:
async def scenario() -> None:
async with open_builtin_runtime(
BuiltinConfig(database=SQLiteConfig()),
handoff_pipeline=_EchoHandoffPipeline(),
) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Working note", summary="Handoff evidence", idempotency_key="working-note-handoff")
)
note = await runtime.sources.for_scope(scope.scope_id).capture_working_note(
CaptureWorkingNote(
source_id="note-1",
content="The malformed-input regression passed locally.",
session_id="session-1",
note_kind=WorkingNoteKind.VALIDATION,
)
)
citation = HandoffSourceCitation(source_ref=note.source_ref)
draft = await runtime.handoff.for_scope(scope.scope_id).prepare(
PrepareHandoff(objective="Continue parser validation.", evidence=(citation,))
)
assert draft.state[0].citations == (citation,)
assert draft.next_action is not None
assert draft.next_action.citations == (citation,)
handoffs = runtime.handoff.for_scope(scope.scope_id)
prepared = await handoffs.finalize(draft)
committed = await handoffs.commit(prepared)
assert committed.content == prepared.content
assert committed.lineage.sources == (note.source_ref,)
assert await handoffs.latest() == committed
asyncio.run(scenario())
def test_handoff_rejects_an_expired_working_note_citation() -> None:
async def scenario() -> None:
async with open_builtin_runtime(
BuiltinConfig(database=SQLiteConfig()),
handoff_pipeline=_EchoHandoffPipeline(),
) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Expired note", summary="Handoff evidence", idempotency_key="expired-note-handoff")
)
with time_machine.travel(datetime(2030, 1, 1, tzinfo=UTC)):
note = await runtime.sources.for_scope(scope.scope_id).capture_working_note(
CaptureWorkingNote(
source_id="expired-note",
content="This validation result is no longer current.",
session_id="session-1",
note_kind=WorkingNoteKind.VALIDATION,
expires_at=datetime(2030, 1, 2, tzinfo=UTC),
)
)
citation = HandoffSourceCitation(source_ref=note.source_ref)
with (
time_machine.travel(datetime(2030, 1, 3, tzinfo=UTC)),
pytest.raises(HandoffEvidenceUnavailableError) as error,
):
await runtime.handoff.for_scope(scope.scope_id).prepare(
PrepareHandoff(objective="Continue parser validation.", evidence=(citation,))
)
assert error.value.citation == citation
stored = await runtime.records.for_scope(scope.scope_id).get_source("content", "expired-note")
assert stored.content == "This validation result is no longer current."
asyncio.run(scenario())
@pytest.mark.parametrize("family", ["unregistered-family", "experience"])
def test_handoff_batch_error_identifies_missing_artifact_after_valid_source(family) -> None:
async def scenario() -> None:
async with open_builtin_runtime(
BuiltinConfig(database=SQLiteConfig()),
handoff_pipeline=_EchoHandoffPipeline(),
) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Batch evidence", summary="Error identity", idempotency_key="batch-error")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(source_id="valid", content="Valid evidence.", metadata={})
)
missing = HandoffArtifactCitation(
artifact_ref=ArtifactRef(family=family, artifact_id="missing", revision=1)
)
with pytest.raises(HandoffEvidenceUnavailableError) as error:
await runtime.handoff.for_scope(scope.scope_id).prepare(
PrepareHandoff(
objective="Report missing evidence.",
evidence=(HandoffSourceCitation(source_ref=source.source_ref), missing),
)
)
assert error.value.citation == missing
assert await runtime.handoff.for_scope(scope.scope_id).latest() is None
asyncio.run(scenario())
def test_handoff_batch_rejects_existing_prompt_as_evidence(tmp_path: Path) -> None:
async def scenario() -> None:
async with open_builtin_runtime(
BuiltinConfig(
database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'prompt-evidence.db'}"),
inference=InferenceConfig(generation_model="test"),
),
handoff_pipeline=_EchoHandoffPipeline(),
) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Prompt boundary", summary="Evidence isolation", idempotency_key="prompt-evidence")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(source_id="valid", content="Valid evidence.", metadata={})
)
prompt = await runtime.records.for_scope(scope.scope_id).create_artifact(
"prompt",
ArtifactWrite(
prompt_key="atomic_memory.extract",
content={
"schema_version": "powercontext.prompt.v1",
"mode": "custom",
"instructions": "Keep personal preferences.",
"demonstrations": [],
},
),
)
citation = HandoffArtifactCitation(
artifact_ref=ArtifactRef(family="prompt", artifact_id=prompt.artifact_id, revision=prompt.revision)
)
handoffs = runtime.handoff.for_scope(scope.scope_id)
with pytest.raises(HandoffEvidenceUnavailableError) as error:
await handoffs.prepare(
PrepareHandoff(
objective="Do not use instructions as evidence.",
evidence=(HandoffSourceCitation(source_ref=source.source_ref), citation),
)
)
assert error.value.citation == citation
assert await handoffs.latest() is None
asyncio.run(scenario())
def test_handoff_batch_error_identifies_source_with_unregistered_definition() -> None:
async def scenario() -> None:
async with SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES) as profile:
original = RelationalContexts(
database=profile.database,
source_registry=SourceDefinitionRegistry.from_adapters(SOURCE_ADAPTERS),
)
context = await original.get("project")
valid = await context.sources.add(await context.sources.resolve(CommitInput(revision="valid")))
unavailable = await context.sources.add(
await context.sources.resolve(NoteInput(note_id="unavailable", body="Historical note."))
)
citations = (
HandoffSourceCitation(source_ref=SourceRef(source_type="commit", source_id=valid.name)),
HandoffSourceCitation(source_ref=SourceRef(source_type="note", source_id=unavailable.name)),
)
# Reopen the same data without the historical Note adapter.
reopened = RelationalContexts(
database=profile.database,
source_registry=SourceDefinitionRegistry.from_adapters((CommitAdapter(),)),
handoff_pipeline=_EchoHandoffPipeline(),
)
handoffs = (await reopened.get("project")).artifacts.handoff
with pytest.raises(HandoffEvidenceUnavailableError) as error:
await handoffs.prepare(PrepareHandoff(objective="Report unavailable evidence.", evidence=citations))
assert error.value.citation == citations[1]
assert await handoffs.latest() is None
asyncio.run(scenario())
def test_runtime_owns_handoff_trigger_activation_and_deduplication() -> None:
async def scenario() -> None:
async with open_builtin_runtime(
BuiltinConfig(database=SQLiteConfig()),
handoff_pipeline=_EchoHandoffPipeline(),
) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Project", summary="Handoff activation", idempotency_key="project")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(
source_id="turn-1",
content="The parser maps malformed input to a stable public error.",
metadata={},
)
)
handoffs = runtime.handoff.for_scope(scope.scope_id)
generated = await handoffs.activate(
ActivateHandoff(
boundary_source=source.source_ref,
objective="Complete parser error handling.",
)
)
ignored = await handoffs.activate(
ActivateHandoff(
boundary_source=source.source_ref,
objective="Complete parser error handling.",
)
)
draft = generated.draft
assert draft is not None
assert generated.status == "generated"
assert generated.current_position == source.sequence
assert ignored.status == "ignored"
assert ignored.draft is None
assert draft.objective == "Complete parser error handling."
assert draft.state[0].citations == (HandoffSourceCitation(source_ref=source.source_ref),)
assert await handoffs.latest() is None
assert (await runtime.capabilities()).handoff_generation is True
asyncio.run(scenario())
def test_handoff_activation_accepts_active_working_note_boundary_and_rejects_expired_note() -> None:
async def scenario() -> None:
async with open_builtin_runtime(
BuiltinConfig(database=SQLiteConfig()),
handoff_pipeline=_EchoHandoffPipeline(),
) as runtime:
assert runtime.scopes is not None
active_scope = await runtime.scopes.create(
ScopeDraft(
title="Active note boundary", summary="Activation evidence", idempotency_key="active-note-boundary"
)
)
active_note = await runtime.sources.for_scope(active_scope.scope_id).capture_working_note(
CaptureWorkingNote(
source_id="active-note-boundary",
content="The current validation state is ready for transfer.",
session_id="session-1",
note_kind=WorkingNoteKind.VALIDATION,
)
)
activation = await runtime.handoff.for_scope(active_scope.scope_id).activate(
ActivateHandoff(
boundary_source=active_note.source_ref,
objective="Continue validation in another session.",
)
)
assert activation.status == "generated"
assert activation.draft is not None
assert activation.draft.state[0].citations == (HandoffSourceCitation(source_ref=active_note.source_ref),)
expired_scope = await runtime.scopes.create(
ScopeDraft(
title="Expired note boundary",
summary="Activation evidence",
idempotency_key="expired-note-boundary",
)
)
with time_machine.travel(datetime(2030, 1, 1, tzinfo=UTC)):
expired_note = await runtime.sources.for_scope(expired_scope.scope_id).capture_working_note(
CaptureWorkingNote(
source_id="expired-note-boundary",
content="This state is no longer current.",
session_id="session-1",
note_kind=WorkingNoteKind.VALIDATION,
expires_at=datetime(2030, 1, 2, tzinfo=UTC),
)
)
with (
time_machine.travel(datetime(2030, 1, 3, tzinfo=UTC)),
pytest.raises(WorkingNoteUnavailableError),
):
await runtime.handoff.for_scope(expired_scope.scope_id).activate(
ActivateHandoff(
boundary_source=expired_note.source_ref,
objective="Do not transfer expired validation state.",
)
)
asyncio.run(scenario())
def test_handoff_activation_rejects_a_lineage_only_boundary_source() -> None:
async def scenario() -> None:
pipeline = _EchoHandoffPipeline()
async with open_builtin_runtime(
BuiltinConfig(database=SQLiteConfig()),
handoff_pipeline=pipeline,
) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Project", summary="Reserved boundary", idempotency_key="reserved-boundary")
)
created = await runtime.records.for_scope(scope.scope_id).create_artifact(
"atomic-memory",
ArtifactWrite(content={"kind": "fact", "text": "Direct input."}),
)
with pytest.raises(SourceNotEligibleError):
await runtime.handoff.for_scope(scope.scope_id).activate(
ActivateHandoff(
boundary_source=created.sources[0],
objective="Do not regenerate from management provenance.",
)
)
asyncio.run(scenario())
def test_handoff_hint_omits_a_lineage_only_source_without_changing_continue_errors() -> None:
async def scenario() -> None:
async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Hint evidence", summary="Eligibility boundary", idempotency_key="hint-eligibility")
)
created = await runtime.records.for_scope(scope.scope_id).create_artifact(
"atomic-memory", ArtifactWrite(content={"kind": "fact", "text": "Direct input."})
)
prepared = PreparedHandoff(
scope_id=scope.scope_id,
base=None,
content=HandoffDraft(
objective="Continue historical work.",
state=(
HandoffStatement(
text="Recorded state.", citations=(HandoffSourceCitation(source_ref=created.sources[0]),)
),
),
disposition="continuable",
).as_content(),
)
handoffs = runtime.handoff.for_scope(scope.scope_id)
hint = await handoffs.hint(PrepareHandoffHint(selection="prepared", prepared=prepared))
assert hint.status == "empty" and hint.content is None and hint.content_bytes == 0
with pytest.raises(SourceNotEligibleError):
await handoffs.continue_from(prepared)
asyncio.run(scenario())
def test_handoff_trigger_state_survives_runtime_restart(tmp_path: Path) -> None:
async def scenario() -> None:
config = BuiltinConfig(
database=SQLiteConfig(
url=f"sqlite+aiosqlite:///{tmp_path / 'trigger.db'}",
)
)
async with open_builtin_runtime(config, handoff_pipeline=_EchoHandoffPipeline()) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Project", summary="Restarted Handoff trigger", idempotency_key="project")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(
source_id="boundary-1",
content="The provider observed one participant boundary.",
metadata={},
)
)
first = await runtime.handoff.for_scope(scope.scope_id).activate(
ActivateHandoff(
boundary_source=source.source_ref,
objective="Transfer the current work.",
)
)
async with open_builtin_runtime(config, handoff_pipeline=_EchoHandoffPipeline()) as runtime:
repeated = await runtime.handoff.for_scope(scope.scope_id).activate(
ActivateHandoff(
boundary_source=source.source_ref,
objective="Transfer the current work.",
)
)
assert first.status == "generated"
assert repeated.status == "ignored"
assert repeated.current_position == source.sequence
asyncio.run(scenario())
def test_handoff_runtime_supports_temporary_transfer_and_durable_milestones() -> None:
async def scenario() -> None:
async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Project", summary="Handoff milestones", idempotency_key="project")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(
source_id="turn-1",
content="The parser maps malformed input to a stable public error.",
metadata={"origin": "e2e"},
)
)
assert runtime.atomic_memory is not None
memory = await runtime.atomic_memory.for_scope(scope.scope_id).create((
AtomicMemoryContent(
kind="decision",
text="Regression tests must use the public parser interface.",
),
))
assert memory.records
source_citation = HandoffSourceCitation(source_ref=source.source_ref)
memory_citation = HandoffArtifactCitation(artifact_ref=memory.primary.ref)
handoffs = runtime.handoff.for_scope(scope.scope_id)
empty = await handoffs.continue_latest()
prepared = await handoffs.finalize(
HandoffDraft(
objective="Complete parser error handling.",
state=(
HandoffStatement(
text="Malformed input now maps to the public error.",
citations=(source_citation,),
),
),
disposition="continuable",
next_action=HandoffStatement(
text="Run public-interface regression tests.",
citations=(source_citation, memory_citation),
),
omissions=(
HandoffOmission(
text="The latest test output was not captured.",
),
),
)
)
assert empty.status == "empty"
assert prepared.base is None
assert await handoffs.latest() is None
assert json.loads(handoffs.render(prepared, audience="human")) == json.loads(
handoffs.render(prepared, audience="agent")
)
transferred = await handoffs.continue_from(prepared)
assert transferred.status == "resolved"
assert transferred.selection == "prepared"
assert transferred.content == prepared.content
assert transferred.selected_revision is None
first = await handoffs.commit(prepared)
retried = await handoffs.commit(prepared)
assert retried == first
assert first.revision == 1
assert first.content == prepared.content
assert first.lineage.sources == (source.source_ref,)
assert first.lineage.artifacts == (memory.primary.ref,)
assert await handoffs.revisions() == (first,)
completed = await handoffs.finalize(
HandoffDraft(
objective=prepared.content.objective,
state=(
HandoffStatement(
text="Public-interface regression tests pass.",
citations=(source_citation, memory_citation),
),
HandoffStatement(
text="The previous milestone remains available for review.",
citations=(HandoffArtifactCitation(artifact_ref=first.as_ref()),),
),
),
disposition="complete",
next_action=None,
)
)
second = await handoffs.commit(completed)
latest = await handoffs.continue_latest()
historical = await handoffs.continue_from(first.as_ref())
assert second.revision == 2
assert second.lineage.artifacts == (memory.primary.ref, first.as_ref())
assert latest.status == "resolved"
assert latest.selection == "latest"
assert latest.selected_revision == second.as_ref()
assert latest.current_revision == second.as_ref()
assert historical.status == "resolved"
assert historical.selection == "exact"
assert historical.selected_revision == first.as_ref()
assert historical.current_revision == second.as_ref()
assert await handoffs.revision(first.as_ref()) == first
assert await handoffs.revisions() == (first, second)
asyncio.run(scenario())
def test_handoff_resolution_authorizes_each_evidence_target_before_reading_it() -> None:
async def scenario() -> None:
async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(
title="Project",
summary="Authorization of Handoff evidence targets.",
idempotency_key="handoff-evidence-authorization",
)
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(source_id="visible", content="Visible evidence.", metadata={})
)
hidden = HandoffArtifactCitation(
artifact_ref=ArtifactRef(family="experience", artifact_id="not-readable", revision=1)
)
prepared = PreparedHandoff(
scope_id=scope.scope_id,
base=None,
content=HandoffDraft(
objective="Continue with independently authorized evidence.",
state=(
HandoffStatement(
text="One citation is visible and one is hidden.",
citations=(HandoffSourceCitation(source_ref=source.source_ref), hidden),
),
),
disposition="continuable",
).as_content(),
)
inspected = []
async def authorize(citation) -> bool:
inspected.append(citation)
return citation != hidden
resolution = await runtime.handoff.for_scope(scope.scope_id).continue_from(
prepared,
evidence_authorizer=authorize,
)
assert inspected == list(prepared.content.state[0].citations)
assert resolution.evidence_checks[0].status == "unavailable"
assert resolution.evidence_checks[0].unavailable_evidence == (hidden,)
asyncio.run(scenario())
def test_handoff_runtime_rejects_stale_and_cross_scope_use() -> None:
async def scenario() -> None:
async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Project", summary="Handoff concurrency", idempotency_key="project")
)
other = await runtime.scopes.create(
ScopeDraft(title="Other", summary="Cross-Scope Handoff", idempotency_key="other")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(
source_id="turn-1",
content="A stable source for concurrent Handoffs.",
metadata={},
)
)
citation = HandoffSourceCitation(source_ref=source.source_ref)
handoffs = runtime.handoff.for_scope(scope.scope_id)
initial = await handoffs.finalize(
HandoffDraft(
objective="Coordinate the next milestone.",
state=(HandoffStatement(text="Initial state.", citations=(citation,)),),
disposition="continuable",
)
)
first = await handoffs.commit(initial)
session_a = await handoffs.finalize(
HandoffDraft(
objective=initial.content.objective,
state=(HandoffStatement(text="Session A state.", citations=(citation,)),),
disposition="continuable",
)
)
session_b = await handoffs.finalize(
HandoffDraft(
objective=initial.content.objective,
state=(HandoffStatement(text="Session B state.", citations=(citation,)),),
disposition="continuable",
)
)
current = await handoffs.commit(session_a)
with pytest.raises(RevisionConflictError) as stale:
await handoffs.commit(session_b)
with pytest.raises(HandoffScopeMismatchError):
await runtime.handoff.for_scope(other.scope_id).continue_from(session_a)
assert stale.value.artifact == session_b.base
assert stale.value.current == current
assert await handoffs.revisions() == (first, current)
asyncio.run(scenario())
def test_handoff_runtime_recovers_only_explicitly_committed_milestones(tmp_path: Path) -> None:
async def scenario() -> None:
config = BuiltinConfig(
database=SQLiteConfig(
url=f"sqlite+aiosqlite:///{tmp_path / 'handoff.db'}",
)
)
async with open_builtin_runtime(config) as runtime:
assert runtime.scopes is not None
scope = await runtime.scopes.create(
ScopeDraft(title="Project", summary="Durable Handoff", idempotency_key="project")
)
source = await runtime.sources.for_scope(scope.scope_id).capture(
CaptureSource(
source_id="turn-1",
content="Persist only an explicitly selected milestone.",
metadata={},
)
)
prepared = await runtime.handoff.for_scope(scope.scope_id).finalize(
HandoffDraft(
objective="Recover the selected milestone.",
state=(
HandoffStatement(
text="The temporary Handoff is ready for transfer.",
citations=(HandoffSourceCitation(source_ref=source.source_ref),),
),
),
disposition="continuable",
next_action=HandoffStatement(
text="Commit the reviewed milestone.",
citations=(HandoffSourceCitation(source_ref=source.source_ref),),
),
)
)
transferred_value = prepared.model_dump_json(by_alias=True)
async with open_builtin_runtime(config) as runtime:
handoffs = runtime.handoff.for_scope(scope.scope_id)
restored_temporary = PreparedHandoff.model_validate_json(transferred_value)
assert (await handoffs.continue_latest()).status == "empty"
assert (await handoffs.continue_from(restored_temporary)).status == "resolved"
committed = await handoffs.commit(restored_temporary)
async with open_builtin_runtime(config) as runtime:
handoffs = runtime.handoff.for_scope(scope.scope_id)
recovered = await handoffs.continue_latest()
assert recovered.status == "resolved"
assert recovered.selection == "latest"
assert recovered.content == prepared.content
assert recovered.selected_revision == committed.as_ref()
assert recovered.current_revision == committed.as_ref()
assert await handoffs.revisions() == (committed,)
asyncio.run(scenario())