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
feat(integrations): resolve server-owned scopes
  • Loading branch information
PsiACE committed Sep 2, 2026
commit 5cce29bdbe9792e2873b90ecd7fb034e1819e10a
46 changes: 19 additions & 27 deletions .github/workflows/build-artifacts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -256,34 +256,26 @@ jobs:
python_executable = f"python{os.environ['PYTHON_VERSION']}"
hooks_path = root / "hooks/hooks.json"
hooks = json.loads(hooks_path.read_text())
recall_hook = hooks["hooks"]["UserPromptSubmit"][0]["hooks"][0]
expected = (
'uv run --locked --quiet --project "${PLUGIN_ROOT}" '
'python "${PLUGIN_ROOT}/hooks/recall.py"'
)
if recall_hook["command"] != expected:
raise SystemExit("unexpected Codex recall command")
recall_hook["command"] = (
'PYTHONPATH="${PLUGIN_ROOT}/vendor" '
+ python_executable
+ ' "${PLUGIN_ROOT}/hooks/recall.py"'
)
hook_scripts = {
"SessionStart": "session_binding.py",
"PreToolUse": "bind_tools.py",
"UserPromptSubmit": "recall.py",
}
for event, script in hook_scripts.items():
hook = hooks["hooks"][event][0]["hooks"][0]
expected = (
'uv run --frozen --quiet --project "${PLUGIN_ROOT}" '
f'python "${{PLUGIN_ROOT}}/hooks/{script}"'
)
if hook["command"] != expected:
raise SystemExit(f"unexpected Codex {event} command")
hook["command"] = (
'PYTHONPATH="${PLUGIN_ROOT}/vendor" '
+ python_executable
+ f' "${{PLUGIN_ROOT}}/hooks/{script}"'
)
hooks_path.write_text(json.dumps(hooks, indent=2) + "\n")

skill_path = root / "skills/project-context/SKILL.md"
skill = skill_path.read_text()
expected_skill = (
'uv run --locked --quiet --project "$PLUGIN_ROOT" python '
'"$PLUGIN_ROOT/scripts/project_scope.py" --cwd "$PWD"'
)
replacement_skill = (
f'PYTHONPATH="$PLUGIN_ROOT/vendor" {python_executable} '
'"$PLUGIN_ROOT/scripts/project_scope.py" --cwd "$PWD"'
)
if skill.count(expected_skill) != 1:
raise SystemExit("unexpected project-context Skill command")
skill_path.write_text(skill.replace(expected_skill, replacement_skill))

readme_path = root / "README.md"
readme = readme_path.read_text()
expected_readme = (
Expand Down Expand Up @@ -381,7 +373,7 @@ jobs:
(
cd "$plugin_root"
PYTHONPATH="$plugin_root/vendor" \
"python${PYTHON_VERSION}" scripts/project_scope.py --cwd "$GITHUB_WORKSPACE"
"python${PYTHON_VERSION}" -m compileall -q hooks scripts
)

- name: Create compressed artifact
Expand Down
4 changes: 3 additions & 1 deletion .licenserc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ header:
- '**/LICENSE'
- 'NOTICE'
- '**/LICENSE.oceanbase-design'
- '**/uv.lock'
- '**/*.lock'
- '**/*-lock.yaml'
- '**/*.lockb'
- 'benchmark/locomo/dataset/**'
- 'benchmark/locomo/results/**'
- 'tox.ini'
Expand Down
48 changes: 30 additions & 18 deletions e2e/bub/src/powercontext_e2e/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
from harbor.models.trial.result import StepResult
from powercontext.client import PowerContextClient
from powercontext.client.settings import ClientSettings
from powercontext.http import ListMemoryEntriesRequest, PrepareContextRequest
from powercontext.http import CreateScopeRequest, ListMemoryEntriesRequest, PrepareContextRequest

from .artifacts import write_artifacts
from .catalog import E2ETask, MemoryEvaluationSpec, OutcomeEvaluationSpec
Expand Down Expand Up @@ -217,30 +217,42 @@ async def run_task_group(
else None
)
run_id = _run_id(tasks)
scopes = {task.id: f"e2e:{run_id}:{task.id}" if runtime else f"e2e:{run_id}" for task in tasks}
runs = {task.id: TaskRun(task, run_id, scopes[task.id], datetime.now(UTC), MemorySnapshot()) for task in tasks}
invocation_scopes = (
tuple(scopes[source.task.id] for source in runtime.sources for _ in source.runtime_steps) if runtime else ()
)
job_config = _job_config(
tasks[0],
run_id,
scopes[tasks[0].id],
output_dir,
settings,
runtime=runtime,
invocation_scopes=invocation_scopes,
)
harbor = HarborTrialObservation()
step_results: tuple[StepResult, ...] = ()
trial_dir: Path | None = None
execution_errors: list[str] = []

async with _powercontext_client() as client:
memory_tasks = tuple(task for task in tasks if isinstance(task.evaluation, MemoryEvaluationSpec))
if memory_tasks:
await client.get_readiness()
started_at = datetime.now(UTC)
scopes = {
task.id: (
await client.create_scope(
CreateScopeRequest(
title=f"E2E workload: {task.id}",
summary=f"Isolated Scope for the {task.id} workload in E2E run {run_id}.",
idempotency_key=f"e2e:{run_id}:{task.id}",
)
)
).scope_id
for task in tasks
}
runs = {task.id: TaskRun(task, run_id, scopes[task.id], started_at, MemorySnapshot()) for task in tasks}
invocation_scopes = (
tuple(scopes[source.task.id] for source in runtime.sources for _ in source.runtime_steps) if runtime else ()
)
job_config = _job_config(
tasks[0],
run_id,
scopes[tasks[0].id],
output_dir,
settings,
runtime=runtime,
invocation_scopes=invocation_scopes,
)
try:
memory_tasks = tuple(task for task in tasks if isinstance(task.evaluation, MemoryEvaluationSpec))
if memory_tasks:
await client.get_readiness()
for task in memory_tasks:
run = runs[task.id]
runs[task.id] = run._replace(memory_before=await memory_snapshot(client, run.scope_id))
Expand Down
5 changes: 5 additions & 0 deletions e2e/bub/tests/test_bub_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ async def capture_content_source(self, request: Any) -> SimpleNamespace:
captured_requests.append(request)
return SimpleNamespace(position=1)

async def resolve_scope_binding(self, request: Any) -> SimpleNamespace:
assert request.explicit_scope_id == "test:scope"
return SimpleNamespace(scope_id="scp_00000000000000000000000000")

settings = PowerContextSettings(
base_url="http://127.0.0.1:8000",
scope_id="test:scope",
Expand Down Expand Up @@ -73,6 +77,7 @@ async def capture_content_source(self, request: Any) -> SimpleNamespace:

assert len(captured_requests) == 1
request = captured_requests[0]
assert request.scope_id == "scp_00000000000000000000000000"
assert request.metadata["event"] == "tool_result"
assert sensitive_value not in request.content
assert "[REDACTED]" in request.content
137 changes: 137 additions & 0 deletions e2e/bub/tests/test_bub_scope_binding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# 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
from pathlib import Path
from types import SimpleNamespace
from typing import Any, ClassVar

from bub.hooks.interception import LlmCallRequest
from powercontext_bub import plugin as plugin_module
from powercontext_bub import tools as tools_module
from powercontext_bub.plugin import STATE_KEY, PowerContextPlugin, PowerContextSettings
from powercontext_bub.scope import workspace_binding_key

RESOLVED_SCOPE_ID = "scp_00000000000000000000000000"


class RecordingClient:
calls: ClassVar[list[tuple[str, Any]]] = []
scope_ids: ClassVar[list[str]] = [RESOLVED_SCOPE_ID]

def __init__(self, base_url: str, *, timeout: float) -> None:
del base_url, timeout

async def __aenter__(self) -> RecordingClient:
return self

async def __aexit__(self, *exc_info: object) -> None:
del exc_info

async def resolve_scope_binding(self, request: Any) -> SimpleNamespace:
self.calls.append(("resolve", request))
index = len([name for name, _ in self.calls if name == "resolve"]) - 1
return SimpleNamespace(scope_id=self.scope_ids[min(index, len(self.scope_ids) - 1)])

async def capture_content_source(self, request: Any) -> SimpleNamespace:
self.calls.append(("capture", request))
return SimpleNamespace(position=1)

async def prepare_context(self, request: Any) -> SimpleNamespace:
self.calls.append(("prepare", request))
return SimpleNamespace(
content="remembered context",
content_bytes=18,
status=SimpleNamespace(value="ready"),
)

async def search_memory(self, request: Any) -> SimpleNamespace:
self.calls.append(("search", request))
return SimpleNamespace(hits=[])


def _plugin(monkeypatch, tmp_path: Path, *, capture_events: bool = False) -> PowerContextPlugin:
settings = PowerContextSettings(
base_url="http://127.0.0.1:8000",
scope_id="configured-scope",
capture_events=capture_events,
capture_checkpoint_every=100,
)
monkeypatch.setattr(plugin_module, "ensure_config", lambda _: settings)
monkeypatch.setattr(plugin_module, "PowerContextClient", RecordingClient)
return PowerContextPlugin(SimpleNamespace(workspace=tmp_path))


def test_workspace_binding_key_is_stable_and_opaque(tmp_path: Path) -> None:
key = workspace_binding_key(tmp_path)
equivalent_key = workspace_binding_key(tmp_path / ".")

assert key is not None
assert key == equivalent_key
assert key.integration == "bub"
assert key.kind == "workspace"
assert str(tmp_path) not in key.external_id


def test_recall_and_capture_use_only_the_server_resolved_scope(monkeypatch, tmp_path: Path) -> None:
RecordingClient.calls.clear()
next_scope_id = "scp_10000000000000000000000000"
RecordingClient.scope_ids = [RESOLVED_SCOPE_ID, next_scope_id]
plugin = _plugin(monkeypatch, tmp_path, capture_events=True)
state = plugin.load_state(message=None, session_id="session-1")
state["session_id"] = "session-1"

request = LlmCallRequest(
run_id="run-1",
model="test-model",
messages=[{"role": "user", "content": "What did we decide?"}],
)
result = asyncio.run(plugin.before_llm_call(request, state))

assert result is not None
assert {call.scope_id for name, call in RecordingClient.calls if name in {"capture", "prepare"}} == {
RESOLVED_SCOPE_ID
}
resolve_requests = [call for name, call in RecordingClient.calls if name == "resolve"]
assert len(resolve_requests) == 1
assert resolve_requests[0].explicit_scope_id == "configured-scope"
assert resolve_requests[0].binding_keys == state[STATE_KEY]["binding_keys"]
assert state[STATE_KEY]["scope_id"] == RESOLVED_SCOPE_ID

asyncio.run(plugin.before_llm_call(request, state))

next_state = plugin.load_state(message=None, session_id="session-2")
next_state["session_id"] = "session-2"
asyncio.run(plugin.before_llm_call(request, next_state))
assert {call.scope_id for name, call in RecordingClient.calls[-2:] if name in {"capture", "prepare"}} == {
next_scope_id
}


def test_tool_resolves_and_caches_the_real_scope_before_search(monkeypatch, tmp_path: Path) -> None:
RecordingClient.calls.clear()
RecordingClient.scope_ids = [RESOLVED_SCOPE_ID]
plugin = _plugin(monkeypatch, tmp_path)
state = plugin.load_state(message=None, session_id="session-1")
context = SimpleNamespace(state=state)

result = asyncio.run(tools_module.search_memory.run(query="database", context=context))

assert result == "(no matching PowerContext memory)"
resolve_request = RecordingClient.calls[0][1]
assert resolve_request.explicit_scope_id == "configured-scope"
assert resolve_request.binding_keys == state[STATE_KEY]["binding_keys"]
assert RecordingClient.calls[1][1].scope_id == RESOLVED_SCOPE_ID
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,17 @@ corresponding tool call returns successfully.

## Resolve Scope

Before the first PowerContext tool call, choose one `scope_id` for the current
task and reuse it for all Memory and Handoff calls in that task.

Prefer a project-scoped identifier that is stable across compatible agents. For
a GitHub repository, use the normalized repository identity when it is known:

```text
git:github.com/owner/repository
```

If the user or host provides an explicit PowerContext scope, use that value.
When scope is ambiguous, ask the user which project scope should hold the
Memory or Handoff.
Before the first data-plane call, use `resolve_scope_binding` to obtain one
Server-owned Scope. Supply an explicit Scope only when the host or user selected
an existing one; otherwise let the Server use its durable binding or default.
Reuse the returned `scope_id` for the task. Never derive or invent a Scope ID
from a repository, directory, branch, Agent, or prompt.

When the user explicitly establishes an independent result boundary, inspect
the current Scope, call `create_scope` with the established Parent and
references, then bind the host identity when the integration supports durable
binding. Creating or switching a Scope is a host action, not an implicit result
of an ordinary Memory or Handoff call.

## Read Memory

Expand Down
7 changes: 6 additions & 1 deletion integrations/bub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ validated by Pydantic before the plugin starts.
| Variable | Default | Purpose |
| --- | --- | --- |
| `POWERCONTEXT_BUB_BASE_URL` | `http://127.0.0.1:8000` | PowerContext Server URL |
| `POWERCONTEXT_BUB_SCOPE_ID` | workspace-derived | Durable scope shared by Bub sessions |
| `POWERCONTEXT_BUB_SCOPE_ID` | unset | Explicit Scope resolved and validated by the Server before use |
| `POWERCONTEXT_BUB_TIMEOUT` | `10` | Client timeout in seconds |
| `POWERCONTEXT_BUB_MAX_BYTES` | `8000` | Maximum prepared-context size |
| `POWERCONTEXT_BUB_CAPTURE_EVENTS` | `false` | Capture completed Bub events as Content Sources |
Expand All @@ -40,6 +40,11 @@ validated by Pydantic before the plugin starts.
| `POWERCONTEXT_BUB_CAPTURE_LOG` | unset | Optional JSONL evidence path; records metadata but not event content |
| `POWERCONTEXT_BUB_TRUST_TRANSPORT_SECURITY` | `false` | Vouch for a plaintext non-loopback `BASE_URL` on an operator-controlled network (for example a private Compose bridge); otherwise such URLs are refused |

The plugin never derives a Scope ID from the current directory, Git metadata, or a workspace path. It asks the Server
to resolve the configured explicit Scope first, then an opaque stable binding key derived from Bub's workspace identity,
and finally the Server default. Only the real Scope returned by the Server is cached and used for recall, capture, and
tools.

Captured tool arguments redact values under credential-like keys. Known credential environment values are also
removed from serialized event content. Keep the PowerContext scope and optional capture log protected because normal
tool output can still contain sensitive project data.
Expand Down
Loading