Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e393793
feat(scope): add durable organization and bindings
PsiACE Sep 2, 2026
a1d0fb0
feat(migration): register existing runtime scopes
PsiACE Sep 2, 2026
99e4088
feat(artifact): publish exact revisions across scopes
PsiACE Sep 2, 2026
bbd4c4a
refactor(scope): replace project reporting with selections
PsiACE Sep 2, 2026
5cce29b
feat(integrations): resolve server-owned scopes
PsiACE Sep 2, 2026
14278d2
test(scope): verify selection and plugin contracts
PsiACE Sep 2, 2026
5d5b550
docs(scope): explain server-owned organization
PsiACE Sep 2, 2026
605701b
refactor(scope): remove legacy runtime migration
PsiACE Sep 2, 2026
d8a637d
fix(scope): retry bindings without savepoints
PsiACE Sep 2, 2026
325f20d
fix(scope): reject unregistered runtime partitions
PsiACE Sep 2, 2026
f45cc69
fix(scope): serialize hierarchy mutations
PsiACE Sep 2, 2026
056dd9e
fix(codex): guard operations by scope mode
PsiACE Sep 2, 2026
5e35afd
fix(publication): reject incomplete memory copies
PsiACE Sep 2, 2026
83f5235
chore: merge master into scope runtime
PsiACE Sep 2, 2026
3daf855
fix(ci): escape plugin shell variable safely
PsiACE Sep 2, 2026
74abed5
chore: merge latest master into scope runtime
PsiACE Sep 3, 2026
015dc00
chore: merge latest master into scope runtime
PsiACE Sep 3, 2026
befc32f
chore: merge latest master into scope runtime
PsiACE Sep 3, 2026
3a14f3a
fix(runtime): preserve referenced scope recall
PsiACE Sep 3, 2026
a7e5e7b
fix(publication): make delivery atomic
PsiACE Sep 3, 2026
94b388a
docs: use registered scope identifiers
PsiACE Sep 3, 2026
e02e10d
chore: merge latest master into scope runtime
PsiACE Sep 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
test(scope): verify selection and plugin contracts
  • Loading branch information
PsiACE committed Sep 2, 2026
commit 14278d262bde3c8803cfe033e0d400d9382eec85
28 changes: 28 additions & 0 deletions tests/builtin/artifacts/handoff/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ async def generate(self, request, /):
class _HandoffBackend(HandoffBackend):
def __init__(self) -> None:
self.history: list[Handoff] = []
self.published: dict[tuple[str, int], Handoff] = {}

async def create(self, artifact_id: str, draft: HandoffArtifactDraft, /) -> Handoff:
if self.history:
Expand All @@ -89,9 +90,14 @@ async def revise(self, base: Handoff, draft: HandoffArtifactDraft, /) -> Handoff
return self._append(base.artifact_id, draft)

async def get(self, reference: ArtifactRef, /) -> Handoff:
if reference.artifact_id != "handoff":
return self.published[(reference.artifact_id, reference.revision)]
return self.history[reference.revision - 1]

async def latest(self, artifact_id: str, /) -> Handoff | None:
published = [handoff for (current_id, _), handoff in self.published.items() if current_id == artifact_id]
if published:
return max(published, key=lambda handoff: handoff.revision)
if not self.history:
return None
assert self.history[-1].artifact_id == artifact_id
Expand Down Expand Up @@ -373,6 +379,28 @@ async def scenario() -> None:
asyncio.run(scenario())


def test_exact_published_revision_is_continuation_input_without_becoming_the_local_head() -> None:
async def scenario() -> None:
service, backend, _ = _service()
published = Handoff(
artifact_id="pub_01kcontinuation",
revision=1,
content=_draft("Published state.").as_content(),
)
backend.published[(published.artifact_id, published.revision)] = published

continued = await service.continue_from(published.as_ref())

assert continued.status == "resolved"
assert continued.selection == "exact"
assert continued.selected_revision == published.as_ref()
assert continued.current_revision == published.as_ref()
assert continued.content == published.content
assert await service.latest() is None

asyncio.run(scenario())


def test_cross_scope_prepared_handoff_is_rejected() -> None:
async def scenario() -> None:
service, _, _ = _service()
Expand Down
39 changes: 37 additions & 2 deletions tests/builtin/runtime/test_prepared_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,20 @@
from powercontext.builtin.artifacts.memory import MemoryHit
from powercontext.builtin.runtime import PrepareContextRequest
from powercontext.builtin.runtime.errors import PreparedContextInvariantError
from powercontext.builtin.runtime.prepared_context import PreparedContextBuilder
from powercontext.builtin.runtime.prepared_context import (
PreparedContextBuilder,
PreparedExperienceCandidates,
PreparedMemoryCandidates,
)

MEMORY_REF = ArtifactRef(family="memory", artifact_id="memory", revision=3)


class _PreparedCitation(TypedDict):
class _PreparedCitation(TypedDict, total=False):
entry_id: str
memory_ref: object
memory: object
artifact: object


class _PreparedItem(TypedDict):
Expand Down Expand Up @@ -173,6 +180,34 @@ def test_builder_prepares_experience_without_a_memory_head_and_keeps_v1_envelope
assert item["content"].endswith("Lesson: Regenerate and inspect the client before contract tests.")


def test_builder_qualifies_only_cross_scope_citations() -> None:
builder = PreparedContextBuilder()
prepared = builder.build_scopes_result(
request=PrepareContextRequest(query="shared evidence"),
current_scope_id="current",
memory_candidates=(
PreparedMemoryCandidates(scope_id="current", memory_ref=MEMORY_REF, hits=(_hit("local", "Local"),)),
PreparedMemoryCandidates(scope_id="shared", memory_ref=MEMORY_REF, hits=(_hit("shared", "Shared"),)),
),
experience_candidates=(PreparedExperienceCandidates(scope_id="shared", hits=(_experience_hit(),)),),
).context

local, experience, shared = _items(prepared.content)
assert local["citation"]["memory_ref"] == MEMORY_REF.model_dump(mode="json")
assert shared["citation"]["memory"] == {
"scope_id": "shared",
"artifact": MEMORY_REF.model_dump(mode="json"),
}
assert experience["citation"]["artifact"] == {
"scope_id": "shared",
"artifact": {
"family": "experience",
"artifact_id": "experience-1",
"revision": 1,
},
}


def test_builder_keeps_memory_primary_and_bounds_experience_share() -> None:
experiences = tuple(_experience_hit(f"experience-{index}") for index in range(1, 5))
prepared = PreparedContextBuilder().build(
Expand Down
49 changes: 49 additions & 0 deletions tests/builtin/runtime/test_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
StatisticsPeriod,
open_builtin_runtime,
)
from powercontext.builtin.scope import ScopeDraft, ScopeSelection
from powercontext.builtin.sources import ContentSource


Expand Down Expand Up @@ -149,3 +150,51 @@ async def scenario() -> None:
assert result.recall.totals.baseline_tokens == estimator.estimate("a") + estimator.estimate("b") == 2

asyncio.run(scenario())


def test_statistics_uses_the_same_all_exact_and_subtree_selection() -> None:
async def scenario() -> None:
async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime:
assert runtime.scopes is not None
root = await runtime.scopes.create(ScopeDraft(title="Root", summary="Root result", idempotency_key="root"))
child = await runtime.scopes.create(
ScopeDraft(
title="Child",
summary="Child result",
parent_scope_id=root.scope_id,
idempotency_key="child",
)
)
other = await runtime.scopes.create(
ScopeDraft(title="Other", summary="Other result", idempotency_key="other")
)
for scope_id in (root.scope_id, child.scope_id, other.scope_id):
await runtime.memory.for_scope(scope_id).remember(
RememberMemoryRequest(entries=(MemoryEntryInput(kind="fact", text=f"Fact for {scope_id}."),))
)

all_statistics = await runtime.statistics.overview(
ScopeSelection(mode="all"),
period=StatisticsPeriod.TODAY,
)
subtree = await runtime.statistics.overview(
ScopeSelection(mode="subtree", root_scope_id=root.scope_id),
period=StatisticsPeriod.TODAY,
)
exact = await runtime.statistics.overview(
ScopeSelection(mode="exact", scope_ids=(child.scope_id,)),
period=StatisticsPeriod.TODAY,
)

assert set(all_statistics.scope_ids) >= {root.scope_id, child.scope_id, other.scope_id}
assert all_statistics.inventory.memory.entries.total == 3
assert subtree.scope_ids == (root.scope_id, child.scope_id)
assert subtree.inventory.memory.entries.total == 2
assert tuple(item.scope_id for item in subtree.by_scope) == (root.scope_id, child.scope_id)
assert [item.inventory.memory.entries.total for item in subtree.by_scope] == [1, 1]
assert exact.scope_ids == (child.scope_id,)
assert exact.inventory.memory.entries.total == 1
assert exact.by_scope[0].scope_id == child.scope_id
assert exact.by_scope[0].inventory == exact.inventory

asyncio.run(scenario())
93 changes: 91 additions & 2 deletions tests/builtin/test_scope_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import re

import pytest
from sqlalchemy.exc import IntegrityError

from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile
from powercontext.builtin.persistence.tables import BUILTIN_TABLES, SOURCES_TABLE
Expand Down Expand Up @@ -96,16 +97,104 @@ def test_concurrent_scope_creation_returns_one_scope(tmp_path) -> None:
async def scenario() -> None:
config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}")
async with SQLiteProfile.open(config, tables=BUILTIN_TABLES) as profile:
scopes = ScopeApplication(profile.database)
scopes = tuple(ScopeApplication(profile.database) for _ in range(8))
draft = ScopeDraft(title="Feature", summary="Concurrent creation", idempotency_key="concurrent")

created = await asyncio.gather(*(scopes.create(draft) for _ in range(8)))
created = await asyncio.gather(*(application.create(draft) for application in scopes))

assert len({scope.scope_id for scope in created}) == 1

asyncio.run(scenario())


def test_concurrent_scope_creation_rejects_a_different_request(tmp_path) -> None:
async def scenario() -> None:
config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}")
async with SQLiteProfile.open(config, tables=BUILTIN_TABLES) as profile:
left = ScopeApplication(profile.database)
right = ScopeApplication(profile.database)

results = await asyncio.gather(
left.create(ScopeDraft(title="Feature", summary="Left", idempotency_key="concurrent")),
right.create(ScopeDraft(title="Feature", summary="Right", idempotency_key="concurrent")),
return_exceptions=True,
)

assert sum(isinstance(result, ScopeIdempotencyConflictError) for result in results) == 1
assert sum(not isinstance(result, BaseException) for result in results) == 1

asyncio.run(scenario())


def test_scope_creation_does_not_hide_an_unrelated_integrity_error() -> None:
async def scenario() -> None:
async with SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES) as profile:
scope_id = "scp_00000000000000000000000000"
left = ScopeApplication(profile.database, id_factory=lambda: scope_id)
right = ScopeApplication(profile.database, id_factory=lambda: scope_id)
await left.create(ScopeDraft(title="Left", summary="Left", idempotency_key="left"))

with pytest.raises(IntegrityError):
await right.create(ScopeDraft(title="Right", summary="Right", idempotency_key="right"))

asyncio.run(scenario())


def test_concurrent_default_bootstrap_returns_one_scope(tmp_path) -> None:
async def scenario() -> None:
config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}")
async with SQLiteProfile.open(config, tables=BUILTIN_TABLES) as profile:
scopes = tuple(ScopeApplication(profile.database) for _ in range(8))

defaults = await asyncio.gather(*(application.bootstrap_default() for application in scopes))

assert len({scope.scope_id for scope in defaults}) == 1
assert await scopes[0].default_scope() == defaults[0]

asyncio.run(scenario())


def test_concurrent_default_and_binding_writes_remain_valid(tmp_path) -> None:
async def scenario() -> None:
config = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}")
async with SQLiteProfile.open(config, tables=BUILTIN_TABLES) as profile:
applications = tuple(ScopeApplication(profile.database) for _ in range(8))
targets = []
for index in range(len(applications)):
targets.append(
await applications[0].create(
ScopeDraft(title=f"Target {index}", summary="Target", idempotency_key=f"target-{index}")
)
)
target_scopes = tuple(targets)
key = ScopeBindingKey(integration="codex", kind="workspace", external_id="shared")

defaults = await asyncio.gather(
*(
application.set_default(target.scope_id)
for application, target in zip(applications, target_scopes, strict=True)
)
)
bindings = await asyncio.gather(
*(
application.bind(key, target.scope_id)
for application, target in zip(applications, target_scopes, strict=True)
)
)

target_ids = {target.scope_id for target in target_scopes}
persisted_default = await applications[0].default_scope()
persisted_binding = await applications[0].binding(key)
assert tuple(defaults) == target_scopes
assert {binding.scope_id for binding in bindings} == target_ids
assert persisted_default is not None
assert persisted_default.scope_id in target_ids
assert persisted_binding is not None
assert persisted_binding.scope_id in target_ids

asyncio.run(scenario())


def test_parent_organizes_without_sharing_and_cannot_form_a_cycle() -> None:
async def scenario() -> None:
async with SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES) as profile:
Expand Down
4 changes: 2 additions & 2 deletions tests/claude_code_plugin/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"hooks",
"hooks.prepared_context",
"scripts",
"scripts.project_scope",
"scripts.workspace_scope",
)


Expand Down Expand Up @@ -82,7 +82,7 @@ def isolated_diagnostic_state(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -
def scope_module(plugin_imports: None) -> ModuleType:
return _load_module(
"powercontext_claude_code_scope",
PLUGIN_ROOT / "scripts" / "project_scope.py",
PLUGIN_ROOT / "scripts" / "workspace_scope.py",
)


Expand Down
67 changes: 31 additions & 36 deletions tests/claude_code_plugin/test_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
import subprocess
import sys
from pathlib import Path
from shutil import which
from types import ModuleType
from typing import Any, cast

import pytest

Expand Down Expand Up @@ -135,33 +135,42 @@ def test_header_helper_emits_configured_authorization_without_logging_it() -> No
assert completed.stderr == ""


@pytest.mark.parametrize(
("remote", "expected"),
[
("https://github.com/OceanBase/powercontext.git", "github.com/OceanBase/powercontext"),
("ssh://git@github.com/OceanBase/powercontext.git", "github.com/OceanBase/powercontext"),
("git@github.com:OceanBase/powercontext.git", "github.com/OceanBase/powercontext"),
],
)
def test_scope_matches_codex_remote_normalization(
def test_scope_resolver_and_workspace_binding_use_the_server(
scope_module: ModuleType,
remote: str,
expected: str,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
assert scope_module.normalize_git_remote(remote) == expected

requests: list[tuple[str, dict[str, object], str]] = []

def test_scope_override_wins(scope_module: ModuleType, tmp_path: Path) -> None:
assert scope_module.resolve_scope_id(str(tmp_path), configured_scope_id="project:explicit") == "project:explicit"
def request(path, payload, *, settings, deadline, method="POST"):
requests.append((path, payload, method))
return {"scope_id": "scp_00000000000000000000000000"}

monkeypatch.setattr(scope_module, "_request_json", request)
settings = scope_module.ClaudeCodePluginSettings(scope_id="scp_00000000000000000000000000")

def test_scope_reads_the_shared_git_private_workstream_binding(scope_module: ModuleType, tmp_path: Path) -> None:
git = which("git")
assert git is not None
subprocess.run([git, "init", "-q", str(tmp_path)], check=True)
resolved = scope_module.resolve_scope_id(
str(tmp_path),
session_id="session-1",
settings=settings,
deadline=float("inf"),
)
bound = scope_module.bind_scope(
str(tmp_path),
resolved,
settings=settings,
deadline=float("inf"),
)

assert scope_module.bind_workstream_scope(str(tmp_path), "handoff-ui-review") == "handoff-ui-review"
assert scope_module.resolve_scope_id(str(tmp_path)) == "handoff-ui-review"
assert bound == resolved
assert requests[0][0] == "/v1/scope-bindings/resolve"
assert requests[0][1]["explicit_scope_id"] == resolved
binding_keys = cast(list[dict[str, Any]], requests[0][1]["binding_keys"])
assert [key["kind"] for key in binding_keys] == ["session", "workspace"]
assert binding_keys[0]["external_id"] == "session-1"
assert binding_keys[1]["external_id"] != str(tmp_path)
assert requests[1][0] == "/v1/scope-bindings"
assert requests[1][2] == "PUT"


@pytest.mark.parametrize(
Expand Down Expand Up @@ -189,20 +198,6 @@ def test_environment_override_controls_prompt_capture(
assert settings_module.ClaudeCodePluginSettings.from_environment().capture_prompts is False


def test_project_context_skill_preserves_explicit_memory_and_handoff_boundaries() -> None:
content = (PLUGIN_ROOT / "skills" / "project-context" / "SKILL.md").read_text()

assert "Do not call `remember_memory` merely" in content
assert "Ordinary prompt Sources are not task outcomes" in content
assert "`select_handoff_workstream`" in content
assert "structured choices" in content
assert "`handoff_current_work`" in content
assert "returned `handoff` member unchanged" in content
assert "`continue_handoff`" in content
assert "`acknowledge_handoff`" in content
assert "`record_task_outcome`" in content


def test_claude_integration_does_not_embed_machine_specific_windows_paths() -> None:
roots = (
REPOSITORY_ROOT / ".claude-plugin",
Expand Down
Loading