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
fix(runtime): preserve referenced scope recall
  • Loading branch information
PsiACE committed Sep 3, 2026
commit 3a14f3aa2f0c7013f249d632535d398a4736f198
57 changes: 51 additions & 6 deletions src/powercontext/builtin/runtime/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,19 +404,20 @@ async def _prepare(self, request: PrepareContextRequest, scope: ScopeDescriptor,

memory_candidates: list[PreparedMemoryCandidates] = []
experience_candidates: list[PreparedExperienceCandidates] = []
remaining_memory = builder.memory_candidate_limit
remaining_experience = builder.experience_candidate_limit
for scope_id in scope_ids:
memory, experiences = await self._recall_scope(
scope_id,
request,
memory_limit=remaining_memory,
experience_limit=remaining_experience,
memory_limit=builder.memory_candidate_limit,
experience_limit=builder.experience_candidate_limit,
)
memory_candidates.append(memory)
experience_candidates.append(experiences)
remaining_memory -= len(memory.hits)
remaining_experience -= len(experiences.hits)
memory_candidates = _limit_memory_candidates(memory_candidates, builder.memory_candidate_limit)
experience_candidates = _limit_experience_candidates(
experience_candidates,
builder.experience_candidate_limit,
)

with self._runtime._stage(
"context.build",
Expand Down Expand Up @@ -532,6 +533,50 @@ async def _recall_scope(
)


def _limit_memory_candidates(
candidates: list[PreparedMemoryCandidates],
limit: int,
) -> list[PreparedMemoryCandidates]:
counts = _round_robin_counts(tuple(len(group.hits) for group in candidates), limit)
return [
PreparedMemoryCandidates(
scope_id=group.scope_id,
memory_ref=group.memory_ref,
hits=group.hits[:count],
)
for group, count in zip(candidates, counts, strict=True)
]


def _limit_experience_candidates(
candidates: list[PreparedExperienceCandidates],
limit: int,
) -> list[PreparedExperienceCandidates]:
counts = _round_robin_counts(tuple(len(group.hits) for group in candidates), limit)
return [
PreparedExperienceCandidates(scope_id=group.scope_id, hits=group.hits[:count])
for group, count in zip(candidates, counts, strict=True)
]


def _round_robin_counts(sizes: tuple[int, ...], limit: int) -> tuple[int, ...]:
counts = [0] * len(sizes)
remaining = limit
while remaining > 0:
advanced = False
for index, size in enumerate(sizes):
if counts[index] >= size:
continue
counts[index] += 1
remaining -= 1
advanced = True
if remaining == 0:
break
if not advanced:
break
return tuple(counts)


class ContextApplication:
"""Select the scoped context-preparation application service."""

Expand Down
41 changes: 23 additions & 18 deletions src/powercontext/builtin/runtime/prepared_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,23 +139,25 @@ def build_scopes_result(
if sum(len(candidates.hits) for candidates in experience_candidates) > self.experience_candidate_limit:
raise PreparedContextInvariantError("experience-candidate-limit")

memory_entries = tuple(
entry
for candidates in memory_candidates
for entry in self._memory_entries(
candidates.memory_ref,
candidates.hits,
scope_id=None if candidates.scope_id == current_scope_id else candidates.scope_id or None,
memory_entries = _interleave_groups(
tuple(
self._memory_entries(
candidates.memory_ref,
candidates.hits,
scope_id=None if candidates.scope_id == current_scope_id else candidates.scope_id or None,
)
for candidates in memory_candidates
)
)
experience_entries = tuple(
entry
for candidates in experience_candidates
for entry in self._experience_entries(
candidates.hits,
scope_id=None if candidates.scope_id == current_scope_id else candidates.scope_id or None,
experience_entries = _interleave_groups(
tuple(
self._experience_entries(
candidates.hits,
scope_id=None if candidates.scope_id == current_scope_id else candidates.scope_id or None,
)
for candidates in experience_candidates
)
)
)[: self.experience_entry_limit]
entries = self._fit_entries(request, memory_entries, experience_entries)

if not entries:
Expand Down Expand Up @@ -190,8 +192,6 @@ def _memory_entries(
seen.add(citation_key)
if not hit.entry_id.strip() or not hit.entry_version_id.strip() or not hit.text.strip():
continue
if len(memory_entries) >= self.entry_limit:
break
citation = MemoryCitation(
memory_ref=hit.memory_ref,
entry_id=hit.entry_id,
Expand Down Expand Up @@ -237,8 +237,6 @@ def _experience_entries(
if identity in seen_experiences:
continue
seen_experiences.add(identity)
if len(experience_entries) >= self.experience_entry_limit:
break
origin: PreparedContextOrigin = hit.artifact_ref
rendered_citation: dict[str, object] = {"artifact_ref": hit.artifact_ref.model_dump(mode="json")}
if scope_id is not None:
Expand Down Expand Up @@ -339,6 +337,13 @@ def _interleave(
return tuple(ordered)


def _interleave_groups(groups: Sequence[Sequence[_PreparedContextEntry]]) -> tuple[_PreparedContextEntry, ...]:
ordered: list[_PreparedContextEntry] = []
for index in range(max((len(group) for group in groups), default=0)):
ordered.extend(group[index] for group in groups if index < len(group))
return tuple(ordered)


def _render(entries: Sequence[_PreparedContextEntry]) -> str:
envelope = {
"trust": "untrusted_history",
Expand Down
41 changes: 41 additions & 0 deletions tests/e2e/test_builtin_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,47 @@ async def scenario() -> None:
asyncio.run(scenario())


def test_prepare_context_keeps_referenced_scope_eligible_when_local_recall_is_full() -> None:
async def scenario() -> None:
async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime:
assert runtime.scopes is not None
shared = await runtime.scopes.create(
ScopeDraft(title="Shared", summary="Reusable evidence", idempotency_key="shared-full-recall")
)
reader = await runtime.scopes.create(
ScopeDraft(
title="Reader",
summary="Reads shared evidence",
context_references=(shared.scope_id,),
idempotency_key="reader-full-recall",
)
)
await runtime.memory.for_scope(reader.scope_id).remember(
RememberMemoryRequest(
entries=tuple(
MemoryEntryInput(kind="fact", text=f"Candidate saturation local evidence {index}.")
for index in range(16)
)
)
)
await runtime.memory.for_scope(shared.scope_id).remember(
RememberMemoryRequest(
entries=(MemoryEntryInput(kind="fact", text="Candidate saturation shared evidence."),)
)
)

prepared = await runtime.context.for_scope(reader.scope_id).prepare(
PrepareContextRequest(query="candidate saturation evidence")
)

assert prepared.status == "ready"
assert prepared.content is not None
items = json.loads(prepared.content.splitlines()[-2])["items"]
assert any(item["citation"].get("memory", {}).get("scope_id") == shared.scope_id for item in items)

asyncio.run(scenario())


class _ConcurrentReranker:
policy_id = "test.concurrent-rerank.v1"

Expand Down