Repository navigation
Expand file tree
/
Copy pathtest_runtime_server.py
More file actions
1227 lines (1136 loc) · 51.5 KB
/
Copy pathtest_runtime_server.py
File metadata and controls
1227 lines (1136 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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
import os
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from uuid import uuid4
import httpx
import pytest
from fastapi.testclient import TestClient
from pydantic import SecretStr
from sqlalchemy.engine import make_url
from powercontext.builtin.artifacts.atomic_memory.extraction import (
AtomicMemoryCandidate,
AtomicMemoryExtractionInput,
AtomicMemoryExtractionOutput,
)
from powercontext.builtin.artifacts.handoff import (
HandoffDraft as RuntimeHandoffDraft,
)
from powercontext.builtin.artifacts.handoff import (
HandoffGenerationRequest,
)
from powercontext.builtin.artifacts.handoff import (
HandoffStatement as RuntimeHandoffStatement,
)
from powercontext.builtin.artifacts.memory import (
EmbeddingProfile,
)
from powercontext.builtin.artifacts.memory.errors import InvalidMemoryCandidateError
from powercontext.builtin.inference import EmbeddingResult, GenerationResult, InferenceConfigurationError
from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile
from powercontext.builtin.persistence.sqlite import SQLiteConfig
from powercontext.builtin.runtime import (
HandoffReportConfig,
InferenceConfig,
ScopedAtomicMemoryApplication,
)
from powercontext.client import PowerContextClient, ServerResponseError
from powercontext.errors import RevisionConflictError
from powercontext.http import (
AcknowledgeHandoffRequest,
ActivateHandoffRequest,
ArtifactAddress,
AtomicMemoryLifecycleRequest,
CaptureContentSourceRequest,
CaptureWorkingNoteRequest,
CommitHandoffRequest,
ContinueHandoffRequest,
CreateScopeRequest,
CreateWorkContractRequest,
ExactScopeSelection,
FinalizeHandoffRequest,
FlushMemoryRequest,
GetHandoffReportRequest,
HandoffCurrentWorkRequest,
HandoffSelection,
HandoffSourceCitation,
ListMemoryChangesRequest,
ListMemoryEntriesRequest,
PrepareContextRequest,
PublishArtifactRequest,
ReadinessStatus,
RecordTaskOutcomeRequest,
RememberMemoryRequest,
ReplaceArtifactRequest,
ReportFormat,
RetireMemoryEntryRequest,
ReviseMemoryEntryRequest,
ScopeSelection,
SearchMemoryRequest,
WorkingNoteKind,
)
from powercontext.http import MemorySearchMode as HttpMemorySearchMode
from powercontext.server.factory import create_server_app
from powercontext.server.settings import McpConfig, ServerSettings
from tests.e2e.dream_support import atomic_memory_pipeline, memory_source_text
_ACCESS_READINESS_CHECKS = {
"access_mode": "disabled",
"authentication_provider": "disabled",
"access_provider": "disabled",
"access_resource_kinds": "server,scope,artifact",
"access_artifact_families": (
"atomic-memory:enabled,experience:enabled,handoff:enabled,memory:enabled,profile:enabled,prompt:enabled,skill:enabled"
),
}
EMBEDDING_PROFILE = EmbeddingProfile(
profile_id="database-e2e-v1",
model="database-e2e",
dimension=3,
distance="l2",
normalization="unit",
)
@pytest.fixture
def database(database_kind: str, tmp_path: Path) -> Iterator[SQLiteConfig | OceanBaseConfig]:
if database_kind == "sqlite":
yield SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}")
return
configured_url = os.environ.get("POWERCONTEXT_TEST_OCEANBASE_URL")
if not configured_url:
pytest.skip("set POWERCONTEXT_TEST_OCEANBASE_URL with test database creation and deletion privileges")
configured = OceanBaseConfig(url=SecretStr(configured_url))
name = f"pc_runtime_{uuid4().hex}"
async def execute(statement: str) -> None:
async with (
OceanBaseProfile.open(configured, tables=()) as profile,
profile.database.transaction() as connection,
):
await connection.exec_driver_sql(statement)
asyncio.run(execute(f"CREATE DATABASE `{name}`"))
try:
url = make_url(configured_url).set(database=name).render_as_string(hide_password=False)
yield OceanBaseConfig(url=SecretStr(url))
finally:
asyncio.run(execute(f"DROP DATABASE `{name}`"))
class ContentCandidatePipeline:
async def generate(self, request: AtomicMemoryExtractionInput, /) -> GenerationResult[AtomicMemoryExtractionOutput]:
return GenerationResult(
output=AtomicMemoryExtractionOutput(
candidates=tuple(
AtomicMemoryCandidate(kind="decision", text=text, evidence_ids=(evidence.evidence_id,))
for evidence in request.evidence
if (text := memory_source_text(evidence)) is not None
)
)
)
class KeywordEmbeddingModel:
profile = EMBEDDING_PROFILE
async def embed(self, texts: tuple[str, ...], /) -> EmbeddingResult:
return EmbeddingResult(
vectors=tuple((1.0, 0.0, 0.0) if "alpha" in text.casefold() else (0.0, 1.0, 0.0) for text in texts)
)
class MisconfiguredEmbeddingModel:
profile = EMBEDDING_PROFILE
async def embed(self, _texts: tuple[str, ...], /) -> EmbeddingResult:
raise InferenceConfigurationError("secret provider response") # noqa: TRY003 - verifies redaction
class DeterministicHandoffPipeline:
async def generate(self, request: HandoffGenerationRequest, /) -> RuntimeHandoffDraft:
citations = tuple(item.citation for item in request.evidence)
return RuntimeHandoffDraft(
objective=request.objective,
state=(
RuntimeHandoffStatement(
text="The HTTP and SDK lifecycle is connected.",
citations=citations,
),
),
disposition="continuable",
next_action=RuntimeHandoffStatement(
text="Continue from the inspected temporary Handoff.",
citations=citations,
),
)
def _server_settings(
database: Path,
*,
generation_model: str | None = None,
mcp: bool = False,
handoff_report: bool = False,
) -> ServerSettings:
return ServerSettings(
database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"),
inference=InferenceConfig(generation_model=generation_model),
handoff_report=HandoffReportConfig(enabled=handoff_report),
mcp=McpConfig(enabled=mcp),
)
@pytest.mark.parametrize("database_kind", ["sqlite", "oceanbase"])
def test_server_databases_share_source_to_memory_search_behavior(
database: SQLiteConfig | OceanBaseConfig,
) -> None:
app = create_server_app(
settings=ServerSettings(
database=database,
mcp=McpConfig(enabled=False),
),
candidate_pipeline=atomic_memory_pipeline(ContentCandidatePipeline()),
)
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
readiness = await client.get_readiness()
capabilities = await client.get_capabilities()
scope = await client.create_scope(
CreateScopeRequest(
title="Database acceptance",
summary="Isolated source-to-memory search acceptance.",
idempotency_key=f"database-e2e-{uuid4()}",
)
)
scope_id = scope.scope_id
captured = await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=scope_id,
source_id="turn-1",
content="Keep the OpenAPI contract authoritative.",
metadata={"channel": "e2e"},
)
)
flushed = await client.flush_memory(FlushMemoryRequest(scope_id=scope_id))
found = await client.search_memory(SearchMemoryRequest(scope_id=scope_id, query="OpenAPI authoritative"))
prepared = await client.prepare_context(
PrepareContextRequest(scope_id=scope_id, query="OpenAPI authoritative")
)
unrelated = await client.search_memory(
SearchMemoryRequest(scope_id=scope_id, query="Should we keep blue icons in mobile navigation?")
)
entries = await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=scope_id))
ref = found.hits[0].memory.artifact
exact = await client.get_artifact_revision(scope_id, ref.family, ref.artifact_id, ref.revision)
assert readiness.checks == {
"runtime": "ready",
"database": "ready",
"artifact_processing_supervisor": "disabled",
**_ACCESS_READINESS_CHECKS,
}
assert capabilities.source_types == ["content"]
assert ref.family == "atomic-memory"
assert ref.family in capabilities.artifact_families
assert "memory" in capabilities.artifact_families
assert capabilities.memory_extraction is True
assert capabilities.search_modes == ["auto", "fts"]
assert capabilities.context_versions == ["powercontext.prepared-context.v1"]
assert captured.position == 1
assert flushed.current_cursor == captured.position
assert flushed.memory is None
assert found.mode == "text"
assert [hit.memory.text for hit in found.hits] == ["Keep the OpenAPI contract authoritative."]
assert prepared.schema_ == "powercontext.prepared-context.v1"
assert prepared.status == "ready"
assert prepared.content is not None
prepared_item = json.loads(prepared.content.splitlines()[-2])["items"][0]
assert prepared_item["content"] == "Keep the OpenAPI contract authoritative."
assert prepared_item["citation"]["artifact_ref"] == ref.model_dump(mode="json", by_alias=True)
assert unrelated.hits == []
assert entries.entries[0].artifact == ref
assert exact.sources[0].source_id == "turn-1"
asyncio.run(scenario())
def test_working_note_http_and_sdk_capture_stays_out_of_memory(tmp_path: Path) -> None:
app = create_server_app(
settings=_server_settings(tmp_path / "working-note.db"),
candidate_pipeline=atomic_memory_pipeline(ContentCandidatePipeline()),
)
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
scope = await client.create_scope(
CreateScopeRequest(
title="Working note",
summary="Session-local evidence",
idempotency_key="working-note-http",
)
)
with pytest.raises(ServerResponseError) as reserved_metadata:
await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=scope.scope_id,
source_id="spoofed-note",
content="Generic capture cannot assign a server-owned Source kind.",
metadata={"kind": "working_note"},
)
)
working_note_metadata = await transport.post(
"/v1/sources/working-notes",
json={
"scope_id": scope.scope_id,
"source_id": "metadata-expiry",
"content": "The public contract does not expose Working Note metadata.",
"session_id": "session-1",
"note_kind": "validation",
"metadata": {"expires_at": "2000-01-01T00:00:00+00:00"},
},
)
captured = await client.capture_working_note(
CaptureWorkingNoteRequest(
scope_id=scope.scope_id,
source_id="note-1",
content="The database migration probe passed locally.",
session_id="session-1",
note_kind=WorkingNoteKind.VALIDATION,
expires_at=datetime.now(UTC) + timedelta(days=1),
)
)
with pytest.raises(ServerResponseError) as expired:
await client.capture_working_note(
CaptureWorkingNoteRequest(
scope_id=scope.scope_id,
source_id="note-expired",
content="This note is already stale.",
session_id="session-1",
note_kind=WorkingNoteKind.VALIDATION,
expires_at=datetime.now(UTC) - timedelta(days=1),
)
)
flushed = await client.flush_memory(FlushMemoryRequest(scope_id=scope.scope_id))
entries = await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=scope.scope_id))
assert captured.source.name == "content"
assert reserved_metadata.value.status_code == 422
assert reserved_metadata.value.code == "invalid_request"
assert working_note_metadata.status_code == 422
assert working_note_metadata.json()["error"]["code"] == "invalid_request"
assert captured.position == 1
assert captured.position == flushed.current_cursor
assert expired.value.status_code == 422
assert expired.value.code == "invalid_request"
assert flushed.memory is None
assert entries.entries == []
asyncio.run(scenario())
@pytest.mark.parametrize("database_kind", ["sqlite", "oceanbase"])
def test_server_databases_keep_case_and_accent_variant_identities_distinct(
database: SQLiteConfig | OceanBaseConfig,
) -> None:
marker = uuid4().hex[:12]
memory_text = "Rotate the production signing key every ninety days."
app = create_server_app(
settings=ServerSettings(database=database, mcp=McpConfig(enabled=False)),
)
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
writer_scope = await client.create_scope(
CreateScopeRequest(
title=f"PC {marker} Alpha",
summary="Writer Scope for case-sensitive isolation acceptance.",
idempotency_key=f"PC-{marker}-Alpha",
)
)
reader_scope = await client.create_scope(
CreateScopeRequest(
title=f"pc {marker} alpha",
summary="Reader Scope for case-sensitive isolation acceptance.",
idempotency_key=f"pc-{marker}-alpha",
)
)
accent_scope = await client.create_scope(
CreateScopeRequest(
title=f"{marker} café",
summary="Writer Scope for accent-sensitive isolation acceptance.",
idempotency_key=f"{marker}-café",
)
)
plain_scope = await client.create_scope(
CreateScopeRequest(
title=f"{marker} cafe",
summary="Reader Scope for accent-sensitive isolation acceptance.",
idempotency_key=f"{marker}-cafe",
)
)
source_scope = await client.create_scope(
CreateScopeRequest(
title=f"{marker} source identity",
summary="Source identity case-sensitivity acceptance.",
idempotency_key=f"{marker}-src",
)
)
scope_ids = {
writer_scope.scope_id,
reader_scope.scope_id,
accent_scope.scope_id,
plain_scope.scope_id,
source_scope.scope_id,
}
assert len(scope_ids) == 5
await client.remember_memory(
RememberMemoryRequest(scope_id=writer_scope.scope_id, kind="fact", text=memory_text)
)
leaked = await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=reader_scope.scope_id))
await client.remember_memory(
RememberMemoryRequest(
scope_id=accent_scope.scope_id,
kind="fact",
text="Espresso is on the third floor.",
)
)
accent_leaked = await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=plain_scope.scope_id))
await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=source_scope.scope_id,
source_id="Turn-1",
content="uppercase turn",
)
)
second = await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=source_scope.scope_id,
source_id="turn-1",
content="lowercase turn",
)
)
assert not leaked.entries
assert leaked.next_cursor is None
assert not accent_leaked.entries
assert second.position == 2
asyncio.run(scenario())
def test_inference_failure_degrades_readiness_without_blocking_database_operations(tmp_path: Path) -> None:
app = create_server_app(
settings=_server_settings(tmp_path / "degraded.db"),
embedding_model=MisconfiguredEmbeddingModel(),
)
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
readiness = await client.get_readiness()
scope_id = (await client.get_default_scope()).scope_id
captured = await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=scope_id,
source_id="turn-1",
content="Database-backed capture remains available.",
)
)
assert readiness.status is ReadinessStatus.DEGRADED
assert readiness.checks == {
"runtime": "ready",
"database": "ready",
"inference.embedding": "misconfigured",
"artifact_processing_supervisor": "disabled",
**_ACCESS_READINESS_CHECKS,
}
assert captured.position == 1
asyncio.run(scenario())
def test_sdk_handoff_lifecycle_reaches_generation_and_persistence(tmp_path: Path) -> None:
app = create_server_app(
settings=_server_settings(tmp_path / "handoff.db"),
handoff_pipeline=DeterministicHandoffPipeline(),
)
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
source_scope = await client.create_scope(
CreateScopeRequest(
title="Source work",
summary="Work prepared for an exact Handoff publication.",
idempotency_key="handoff-e2e-source",
)
)
target_scope = await client.create_scope(
CreateScopeRequest(
title="Target work",
summary="Work continued from an exact Handoff publication.",
idempotency_key="handoff-e2e-target",
)
)
scope_id = source_scope.scope_id
capabilities = await client.get_capabilities()
captured = await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=scope_id,
source_id="turn-1",
content="The end-to-end Handoff lifecycle must remain explicit.",
)
)
activation = await client.activate_handoff(
ActivateHandoffRequest(
scope_id=scope_id,
boundary_source=captured.source,
objective="Transfer the current implementation state.",
)
)
repeated = await client.activate_handoff(
ActivateHandoffRequest(
scope_id=scope_id,
boundary_source=captured.source,
objective="Transfer the current implementation state.",
)
)
draft = activation.draft
assert draft is not None
inspected = draft.model_copy(
update={
"state": [
draft.state[0].model_copy(
update={"text": "The full HTTP and SDK lifecycle is connected."},
)
]
}
)
prepared = await client.finalize_handoff(FinalizeHandoffRequest(scope_id=scope_id, draft=inspected))
temporary = await client.continue_handoff(
ContinueHandoffRequest(
scope_id=scope_id,
selection=HandoffSelection.PREPARED,
prepared=prepared,
)
)
committed = await client.commit_handoff(CommitHandoffRequest(scope_id=scope_id, handoff=prepared))
exact = await client.continue_handoff(
ContinueHandoffRequest(
scope_id=scope_id,
selection=HandoffSelection.EXACT,
revision=committed.reference,
)
)
latest = await client.continue_handoff(
ContinueHandoffRequest(
scope_id=scope_id,
selection=HandoffSelection.LATEST,
)
)
publication = await client.publish_artifact(
PublishArtifactRequest(
source=ArtifactAddress(scope_id=scope_id, artifact=committed.reference),
target_scope_id=target_scope.scope_id,
idempotency_key="handoff-e2e-publication",
)
)
published = await client.continue_handoff(
ContinueHandoffRequest(
scope_id=target_scope.scope_id,
selection=HandoffSelection.EXACT,
revision=publication.target.artifact,
)
)
assert capabilities.artifact_families == [
"memory",
"atomic-memory",
"topic-memory",
"experience",
"skill",
"handoff",
"profile",
"prompt",
]
assert capabilities.handoff_generation is True
assert activation.status == "generated"
assert repeated.status == "ignored"
assert repeated.draft is None
assert draft.state[0].text == "The HTTP and SDK lifecycle is connected."
assert prepared.base is None
assert temporary.selection == "prepared"
assert temporary.selected_revision is None
assert temporary.content is not None
assert temporary.content.state[0].text == "The full HTTP and SDK lifecycle is connected."
assert committed.reference.family == "handoff"
assert committed.source_refs == [captured.source]
assert exact.selection == "exact"
assert exact.selected_revision == committed.reference
assert latest.selection == "latest"
assert latest.selected_revision == committed.reference
assert published.selection == "exact"
assert published.selected_revision == publication.target.artifact
assert published.current_revision == publication.target.artifact
assert published.content == committed.content
asyncio.run(scenario())
def test_sdk_closes_the_delegation_handoff_and_outcome_loop(tmp_path: Path) -> None:
app = create_server_app(settings=_server_settings(tmp_path / "work-continuity.db", handoff_report=True))
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
scope_response = await transport.post(
"/v1/scopes",
json={
"title": "Work continuity",
"summary": "Delegation Handoff and outcome loop",
"idempotency_key": "work-continuity-e2e",
},
)
scope_response.raise_for_status()
scope_id = scope_response.json()["scope_id"]
contract = await client.create_work_contract(
CreateWorkContractRequest.model_validate({
"scope_id": scope_id,
"source_id": "contract-1",
"contract": {
"schema": "powercontext.work-contract.v1",
"trust": "untrusted_input",
"objective": "Implement and verify the work-continuity loop.",
"facts": [
{
"text": "The repository already has an explicit Handoff lifecycle.",
"basis": "declared",
"evidence": [],
}
],
"in_scope": ["Reuse the existing Handoff Artifact."],
"exclusions": ["Do not add an Agent scheduler."],
"completion_criteria": ["A receiver can acknowledge exact Handoff evidence."],
"authorization_notes": ["This record does not grant tool execution authority."],
"open_questions": [],
},
})
)
prepared = await client.handoff_current_work(
HandoffCurrentWorkRequest.model_validate({
"scope_id": scope_id,
"source_id": "boundary-1",
"handoff": {
"schema": "powercontext.current-work-handoff.v1",
"trust": "untrusted_input",
"objective": "Implement and verify the work-continuity loop.",
"state": [
{
"text": "The high-level Runtime path is implemented.",
"basis": "declared",
"evidence": [],
}
],
"disposition": "continuable",
"next_action": {
"text": "Run the public Server acceptance test.",
"basis": "declared",
"evidence": [],
},
"omissions": ["Live OceanBase validation is not part of this SQLite acceptance test."],
},
})
)
temporary_acknowledgement = await client.acknowledge_handoff(
AcknowledgeHandoffRequest.model_validate({
"scope_id": scope_id,
"source_id": "receipt-temporary-1",
"receiver": "codex-receiver",
"status": "accepted",
"selection": HandoffSelection.PREPARED,
"receiver_checks": {
"live_state": "confirmed",
"capability": "confirmed",
"authorization": "confirmed",
},
"prepared": prepared.handoff,
})
)
committed = await client.commit_handoff(CommitHandoffRequest(scope_id=scope_id, handoff=prepared.handoff))
durable_acknowledgement = await client.acknowledge_handoff(
AcknowledgeHandoffRequest.model_validate({
"scope_id": scope_id,
"source_id": "receipt-durable-1",
"receiver": "human-reviewer",
"status": "accepted",
"selection": "exact",
"receiver_checks": {
"live_state": "confirmed",
"capability": "confirmed",
"authorization": "confirmed",
},
"revision": committed.reference,
})
)
outcome = await client.record_task_outcome(
RecordTaskOutcomeRequest.model_validate({
"scope_id": scope_id,
"source_id": "outcome-1",
"outcome": {
"schema": "powercontext.task-outcome.v1",
"trust": "untrusted_observation",
"objective": "Implement and verify the work-continuity loop.",
"status": "succeeded",
"summary": "The public SQLite Server journey completed.",
"handoff_receipt_ref": durable_acknowledgement.receipt.source.model_dump(),
"observations": [
{
"text": "Both temporary and committed Handoffs were acknowledged.",
"basis": "declared",
"evidence": [],
}
],
"checks": [
{
"name": "SQLite Server acceptance",
"status": "passed",
"basis": "declared",
"evidence": [],
}
],
"produced_artifacts": [],
"remaining_work": [],
},
})
)
report = await client.get_handoff_report(
GetHandoffReportRequest(
selection=ScopeSelection(root=ExactScopeSelection(mode="exact", scope_ids=[scope_id])),
format=ReportFormat.JSON,
)
)
assert contract.kind == "work-contract"
assert contract.position == 1
assert prepared.boundary.kind == "handoff-boundary"
assert prepared.boundary.position == 2
citation = prepared.handoff.content.state[0].citations[0].root
assert isinstance(citation, HandoffSourceCitation)
assert citation.source_ref == prepared.boundary.source
assert temporary_acknowledgement.resolution.selection == "prepared"
assert temporary_acknowledgement.receipt.kind == "handoff-receipt"
assert temporary_acknowledgement.receipt.position == 3
assert committed.source_refs == [prepared.boundary.source]
assert durable_acknowledgement.resolution.selection == "exact"
assert durable_acknowledgement.resolution.selected_revision == committed.reference
assert durable_acknowledgement.receipt.position == 4
assert outcome.kind == "task-outcome"
assert outcome.position == 5
assert not isinstance(report, str)
assert report.report is not None
assert report.report["scope_ids"] == [scope_id]
assert report.report["scopes"][0]["handoff"] == {
"scope_id": scope_id,
"artifact": committed.reference.model_dump(mode="json"),
}
assert report.report["scopes"][0]["content"]["objective"] == ("Implement and verify the work-continuity loop.")
asyncio.run(scenario())
@pytest.mark.parametrize("database_kind", ["sqlite", "oceanbase"])
def test_server_databases_share_vector_and_hybrid_search_behavior(
database: SQLiteConfig | OceanBaseConfig,
) -> None:
app = create_server_app(
settings=ServerSettings(
database=database,
mcp=McpConfig(enabled=False),
),
candidate_pipeline=atomic_memory_pipeline(ContentCandidatePipeline()),
embedding_model=KeywordEmbeddingModel(),
)
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
capabilities = await client.get_capabilities()
scope = await client.create_scope(
CreateScopeRequest(
title="Vector search acceptance",
summary="Isolated vector and hybrid search acceptance.",
idempotency_key=f"vector-e2e-{uuid4()}",
)
)
scope_id = scope.scope_id
await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=scope_id,
source_id="alpha-source",
content="Alpha semantic record.",
)
)
await client.capture_content_source(
CaptureContentSourceRequest(
scope_id=scope_id,
source_id="beta-source",
content="Beta semantic record.",
)
)
flushed = await client.flush_memory(FlushMemoryRequest(scope_id=scope_id))
vector = await client.search_memory(
SearchMemoryRequest(
scope_id=scope_id,
query="alpha",
mode=HttpMemorySearchMode.VECTOR,
)
)
hybrid = await client.search_memory(
SearchMemoryRequest(
scope_id=scope_id,
query="alpha",
mode=HttpMemorySearchMode.HYBRID,
)
)
assert flushed.memory is None
assert capabilities.search_modes == ["auto", "fts", "vector", "hybrid"]
assert [hit.memory.text for hit in vector.hits] == ["Alpha semantic record."]
assert vector.hits[0].matched_by == ["vector"]
assert [hit.memory.text for hit in hybrid.hits] == ["Alpha semantic record."]
assert hybrid.hits[0].matched_by == ["text", "vector"]
asyncio.run(scenario())
def test_sdk_memory_lifecycle_reaches_one_composed_runtime(tmp_path: Path) -> None:
app = create_server_app(settings=_server_settings(tmp_path / "runtime.db"))
async def scenario() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
scope_id = (await client.get_default_scope()).scope_id
remembered = await client.remember_memory(
RememberMemoryRequest(scope_id=scope_id, kind="decision", text="Use strict transport models.")
)
assert len(remembered.records) == 1
original = remembered.records[0]
ref = original.artifact
exact = await client.get_artifact_revision(scope_id, ref.family, ref.artifact_id, ref.revision)
path = f"/v1/scopes/{scope_id}/artifacts/atomic-memory/{ref.artifact_id}"
head = await transport.get(path)
revised = await client.replace_artifact(
scope_id,
ref.family,
ref.artifact_id,
ReplaceArtifactRequest.model_validate({
"content": {"kind": "decision", "text": "Keep strict Pydantic transport models."}
}),
expected_etag=head.headers["ETag"],
)
state = await client.get_atomic_memory_state(scope_id, ref.artifact_id)
forgotten = await client.change_atomic_memory_lifecycle(
AtomicMemoryLifecycleRequest.model_validate({
"scope_id": scope_id,
"target": {
"artifact": state.artifact.model_dump(mode="json"),
"state_version": state.state_version,
},
"state": "forgotten",
})
)
current = await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=scope_id))
audited = await client.list_memory_entries(
ListMemoryEntriesRequest(scope_id=scope_id, include_inactive=True)
)
forgotten_search = await client.search_memory(
SearchMemoryRequest(scope_id=scope_id, query="strict Pydantic transport models")
)
forgotten_exact = await client.get_artifact_revision(
scope_id, ref.family, ref.artifact_id, revised.revision
)
legacy = {
"memory_ref": {"family": "memory", "artifact_id": "legacy-collection", "revision": 1},
"entry_id": "legacy-entry",
"entry_version_id": "legacy-version",
}
with pytest.raises(ServerResponseError) as inactive:
await client.revise_memory_entry(
ReviseMemoryEntryRequest(
scope_id=scope_id, citation=legacy, kind="decision", text="Rejected legacy revision."
)
)
with pytest.raises(ServerResponseError) as retired:
await client.retire_memory_entry(RetireMemoryEntryRequest(scope_id=scope_id, citation=legacy))
with pytest.raises(ServerResponseError) as changes:
await client.list_memory_changes(ListMemoryChangesRequest(scope_id=scope_id, since_revision=1))
with pytest.raises(ServerResponseError) as missing:
await client.get_artifact_revision(scope_id, ref.family, "missing-memory", 1)
assert (
await client.list_memory_entries(ListMemoryEntriesRequest(scope_id=scope_id, include_inactive=True))
== audited
)
assert exact.content["text"] == "Use strict transport models."
assert revised.content["text"] == "Keep strict Pydantic transport models."
assert revised.revision == ref.revision + 1
assert forgotten.records[0].state == "forgotten"
assert current.entries == []
assert audited.entries == forgotten.records
assert forgotten_search.hits == []
assert forgotten_exact.content == revised.content
for error in (inactive.value, retired.value, changes.value):
assert (error.status_code, error.code) == (422, "legacy_memory_operation_unsupported")
assert missing.value.status_code == 404
asyncio.run(scenario())
def test_runtime_conflicts_keep_http_and_sdk_error_context(tmp_path: Path) -> None:
app = create_server_app(settings=_server_settings(tmp_path / "runtime.db"))
with TestClient(app) as transport:
default_scope = transport.get("/v1/scopes/default")
default_scope.raise_for_status()
scope_id = default_scope.json()["scope_id"]
first = transport.post(
"/v1/sources/content",
json={"scope_id": scope_id, "source_id": "turn-1", "content": "first"},
)
conflict = transport.post(
"/v1/sources/content",
json={"scope_id": scope_id, "source_id": "turn-1", "content": "changed"},
)
assert first.status_code == 202
assert conflict.status_code == 409
assert len(conflict.headers["X-PowerContext-Request-ID"]) == 16
assert int(conflict.headers["X-PowerContext-Request-ID"], 16) > 0
assert conflict.json()["error"]["code"] == "source_conflict"
async def stale_revision() -> None:
async with (
app.router.lifespan_context(app),
httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
) as transport,
):
client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True)
remembered = await client.remember_memory(
RememberMemoryRequest(scope_id=scope_id, kind="decision", text="first")
)
with pytest.raises(ServerResponseError) as caught:
await client.remember_memory(
RememberMemoryRequest(
scope_id=scope_id,
kind="decision",
text="stale",
expected_revision=remembered.records[0].artifact.revision + 1,