Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(harness): bind background commands to their own caller context (#2041)
Call White56ecc789fbdc
diff --git a/core/caller_context.py b/core/caller_context.pyindex f8d1a0285..460b8b9f9 100644--- a/core/caller_context.py+++ b/core/caller_context.py@@ -268,6 +268,21 @@ def caller_resource_user_context(context: Optional[CallerContext]) -> Optional[Mreturn dict(context.resource_user_context or {})+def caller_resource_user_context_from_env(+ env: Mapping[str, str] | None = None,+) -> Optional[Mapping[str, Any]]:+ """Read remote authority independently of a callback Session binding.++ A scheduled command can carry remote authorization without an Agent Session.+ Missing or malformed declared-remote provenance still fails closed.+ """++ source = os.environ if env is None else env+ if not env_declares_remote_caller(source):+ return None+ return _resource_context_from_env(source) or {}++def environment_without_caller_context(env: Optional[Mapping[str, str]] = None) -> dict[str, str]:"""Return ``env`` with this invocation's caller provenance removed.@@ -287,7 +302,38 @@ def environment_without_caller_context(env: Optional[Mapping[str, str]] = None)"""source = os.environ if env is None else env- return {key: value for key, value in source.items() if key not in CALLER_CONTEXT_ENV_NAMES}+ return {+ key: value for key, value in source.items()+ if key not in CALLER_CONTEXT_ENV_NAMES and key != AVIBE_CALLER_SESSION_PROOF_ENV+ }+++def background_command_env(+ *,+ session_id: str | None,+ source: str,+ metadata: Mapping[str, Any],+ run_id: str | None = None,+) -> dict[str, str]:+ """Replace service caller provenance with this definition's execution facts.++ A command is not the human turn that created its definition. Its current+ binding owns CLI defaults and callbacks; creator metadata is not a fallback.+ Only the definition's resource snapshot carries remote authority, rechecked+ by runtime admission and the CLI, never a transient human/Memory proof.+ """++ env = environment_without_caller_context()+ env[AVIBE_CALLER_SOURCE_ENV] = source+ if session_id:+ env[AVIBE_SESSION_ID_ENV] = session_id+ if run_id:+ env[AVIBE_RUN_ID_ENV] = run_id+ snapshot = metadata.get(_RESOURCE_USER_CONTEXT_METADATA_KEY)+ if isinstance(snapshot, Mapping):+ env[AVIBE_CALLER_REMOTE_ENV] = "1"+ env[AVIBE_CALLER_RESOURCE_CONTEXT_ENV] = json.dumps(dict(snapshot), separators=(",", ":"), sort_keys=True)+ return envdef validated_caller_env_snapshot(source: object) -> dict[str, str]:diff --git a/core/command_runner.py b/core/command_runner.pyindex a62828712..558858dd6 100644--- a/core/command_runner.py+++ b/core/command_runner.py@@ -275,6 +275,7 @@ async def run_supervised_command(label: str,on_spawn: Optional[Callable[[int, Optional[PersistedProcessIdentity]], None]] = None,max_output_bytes: Optional[int] = None,+ env: Optional[Mapping[str, str]] = None,extra_env: Optional[Mapping[str, str]] = None,remove_env: Collection[str] = (),discard_stderr: bool = False,@@ -283,7 +284,9 @@ async def run_supervised_command(``timeout_seconds <= 0`` means no timeout. ``max_output_bytes`` of ``None``keeps exact ``communicate()`` semantics; a value caps the retained bytes per- stream while still draining the child to EOF. ``extra_env`` is added to the+ stream while still draining the child to EOF. ``env`` is the complete base+ environment when supplied; otherwise the current process is inherited.+ ``extra_env`` is added to theenvironment the supervisor hands the command, for context the command can onlylearn from its caller; ``remove_env`` then deletes inherited keys. The runner'sprocess-identity marker is restored after both operations. ``discard_stderr``@@ -292,7 +295,7 @@ async def run_supervised_command("""worker_marker = new_process_identity_marker()- spawn_env = process_identity_subprocess_env(worker_marker)+ spawn_env = dict(env) if env is not None else process_identity_subprocess_env(worker_marker)if extra_env:spawn_env.update(extra_env)for key in remove_env:diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex bd5cb165a..6ba863c6e 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -75,6 +75,7 @@ from storage.agent_session_rows import (from storage.db import create_sqlite_engine, get_cached_sqlite_enginefrom core import failure_noticesfrom core.backend_failure import emit_replayed_backend_failure+from core.caller_context import background_command_envfrom core.command_runner import (SupervisedCommandStartupError,command_line_preview,@@ -8691,6 +8692,12 @@ class ScheduledTaskService:execution_id, identity),max_output_bytes=COMMAND_TASK_OUTPUT_CAP_BYTES,+ env=background_command_env(+ session_id=task.session_id,+ source="scheduled_task",+ metadata=task.metadata,+ run_id=execution_id,+ ),)except SupervisedCommandStartupError as exc:# Its own clause, BEFORE the broad one: the class subclassesdiff --git a/core/watches.py b/core/watches.pyindex e4f0ac545..123395cce 100644--- a/core/watches.py+++ b/core/watches.py@@ -17,6 +17,7 @@ from uuid import uuid4from config import pathsfrom config.atomic_io import write_atomicfrom core import watch_worker+from core.caller_context import background_command_envfrom core.command_runner import SupervisedCommandStartupError, run_supervised_commandfrom core.process_isolation import (DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,@@ -2386,6 +2387,11 @@ class ManagedWatchService:label=f"watch {watch.id}",on_spawn=_register_spawn,max_output_bytes=None,+ env=background_command_env(+ session_id=watch.session_id,+ source="watch",+ metadata=watch.metadata,+ ),# Which watch this waiter belongs to. A waiter that keeps persistent# state per watch -- cursor files, locks -- cannot otherwise tell# itself apart from an identically configured sibling watch, and twodiff --git a/docs/plans/background-command-caller-context.md b/docs/plans/background-command-caller-context.mdnew file mode 100644index 000000000..aeb432218--- /dev/null+++ b/docs/plans/background-command-caller-context.md@@ -0,0 +1,63 @@+# Background command caller context++## Problem and scope++A Watch correctly bound to Session B ran a Vault CLI subprocess with Session A+inherited from a long-lived service. The Vault request persisted A, so its expiry+callback correctly followed the wrong creation-time identity. Clearing service+provenance (PR2034) alone leaves the waiter without B.++Repair the shared background-command boundary for Watch waiters and scheduled+commands. Keep existing Vault request/callback behavior, definition ownership,+Session policies, resource authorization, and process supervision.++## Contract++- A command's caller Session is its definition's current explicit `session_id`,+ never the service's caller or the definition creator's old Session.+- An unbound command remains unbound. Legacy `session_key` and create-per-run+ definitions do not create or guess a Session just to run a command.+- Remove inherited caller provenance and the transient Session proof before+ spawning, then supply only the current background source, bound Session,+ actual command Run id when one exists, and the definition's stored remote+ authorization snapshot. Never impersonate a human turn or mint Memory proof.+- Remote commands retain remote authority even without a callback Session.+ Existing runtime admission and CLI authorization revalidate that snapshot;+ malformed provenance must not become local-owner authority.+- Keep ordinary process configuration, Watch cursor/delivery variables, and+ process-identity lifecycle unchanged. Other supervised-command consumers keep+ their existing environment behavior.++## Implementation and validation++1. Reuse caller-context sanitization, including removal of its transient proof.+2. Let the generic command runner accept a complete environment; Watch and Task+ producers compose theirs from definition-owned facts.+3. Let CLI authority read remote provenance independently of a callback Session.+4. Test real supervised child processes with a contaminated and clean parent,+ explicit/absent/changed target bindings, both argv and shell forms, unchanged+ ordinary configuration, and remote authority.+5. Drive the child's real Vault CLI context into isolated access-request expiry+ and callback resolution. Use synthetic sealed envelopes, never live secrets,+ Vault requests, grants, or email. Verify the negative control fails before+ the source fix and passes after it.+6. Run focused tests, related Harness/Vault/permission suites, changed Python+ lint, exact-head CI, and automated Codex review through one durable Watch.++## Known by design++- No historical requests are rewritten or replayed.+- This source PR does not upgrade/restart the running host or resume failed+ automation. Released-host verification requires separate authorization.+- A command without a bound Session cannot automatically resume an Agent+ through Vault; explicit CLI targeting remains available.+- The callback consumer and credential grants are not changed to compensate+ for bad producer identity. No new storage schema or alternate routing owner.++## Local acceptance++HFR-486 reproduced both original failures before the change. The accepted+related suites passed 1,463 tests; four skips are two Windows-only worker+contracts on macOS and two Organization-only denial shapes in the Personal+instance matrix. Pinned Ruff 0.4.9 passed. These are isolated source/process+tests, not a running-host upgrade or live provider/credential trial.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex be495a71c..56958b3d2 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -199,6 +199,7 @@ capabilities:- tests/test_agent_run_target.py- tests/test_watches.py- tests/test_cli_watch_command.py+ - tests/test_background_command_caller_context.py- id: harness_command_taskname: Scheduled command tasks and their failure visibilitystatus: activediff --git a/tests/scenarios/harness_command_task/catalog.yaml b/tests/scenarios/harness_command_task/catalog.yamlindex 33ba56660..a686e0098 100644--- a/tests/scenarios/harness_command_task/catalog.yaml+++ b/tests/scenarios/harness_command_task/catalog.yaml@@ -690,3 +690,10 @@ scenarios:# The shared mapper cases in harnessLifecycle.test.ts cover timeout, nonzero,# and unknown Task/Watch failures, including stderr that looks like another# category. The Watch rendering case proves the same collapsed disclosure.+ - id: SCT-062+ name: command fires carry their current binding and Run without borrowing the service caller+ status: covered+ kind: routing+ layer: scenario+ backend: shared+ test: tests/test_scheduled_command_task_integration.py::test_sct_062_command_fire_replaces_service_caller_with_definition_bindingdiff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 2c468c44c..1589eb1b2 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -4392,6 +4392,15 @@ scenarios:# snapshot capture must converge without a resume or another definition write.# Unchanged snapshots retain worker identity; consumed disables still stop it.test: tests/test_watches.py::test_hfr_485_watch_reconciles_after_another_reader_consumes_reload+ - id: HFR-486+ name: Watch commands and Vault callbacks use the current binding without inherited service identity+ status: covered+ kind: routing+ layer: scenario+ backend: shared+ test: tests/test_background_command_caller_context.py::test_hfr_486_watch_child_vault_callback_uses_only_current_binding+ # Real argv/shell children with clean/contaminated parents, bound/unbound+ # targets, isolated Vault expiry, retargeting, and remote snapshot transport.manual_evidence:- local Incus backend process death after prompt acceptance- local Incus controller restart with persisted queued successordiff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yamlindex bb53dffd6..70736aee8 100644--- a/tests/scenarios/harness_failure_recovery/observations.yaml+++ b/tests/scenarios/harness_failure_recovery/observations.yaml@@ -325,3 +325,15 @@ observations:Prior reload and single-flight tests did not connect that reader ordering toactual scheduling. Always reconciling the captured snapshot retains existingworker identity and avoids adding a second change-acknowledgement mechanism.+ - id: HFR-OBS-027+ date: 2026-09-18+ source: released-host callback diagnosis and isolated real-child negative control+ result: confirmed+ detail: >-+ A correctly bound Watch inherited a different Session from the long-lived+ service, and Vault persisted that identity before routing an expiry callback.+ A clean parent instead lost the bound Session entirely. HFR-486 closes the+ producer-to-consumer chain through real supervised children and isolated+ Vault expiry. Runtime restart sanitization alone cannot supply the binding;+ command execution must replace provenance from its own definition, preserving+ remote authority without borrowing the creator's transient proof.diff --git a/tests/scenarios/permissions/test_cli_invocation_authority.py b/tests/scenarios/permissions/test_cli_invocation_authority.pyindex 35ac7f471..ed2537660 100644--- a/tests/scenarios/permissions/test_cli_invocation_authority.py+++ b/tests/scenarios/permissions/test_cli_invocation_authority.py@@ -25,6 +25,7 @@ import pytestfrom core.caller_context import (AVIBE_CALLER_RESOURCE_CONTEXT_ENV,+ AVIBE_SESSION_ID_ENV,CALLER_CONTEXT_ENV_NAMES,CallerContext,)@@ -186,9 +187,12 @@ def test_permissions_026_every_cli_command_declares_a_role_floor():("owner", "owner", True),],)-def test_permissions_026_authority_comes_from_the_caller_env(caller, expected_role, expected_remote):[email protected]("bound_session", [False, True])+def test_permissions_026_authority_comes_from_the_caller_env(caller, expected_role, expected_remote, bound_session):"""PERMISSIONS-026: the snapshot the host injected is the authority the CLI runs under."""env = _caller_env(None if caller == "local" else caller)+ if not bound_session:+ env.pop(AVIBE_SESSION_ID_ENV, None)authority = cli._cli_invocation_authority(env)if caller == "local":@@ -201,9 +205,12 @@ def test_permissions_026_authority_comes_from_the_caller_env(caller, expected_ro@pytest.mark.parametrize("provenance", ["missing", "malformed", "not_an_object"])-def test_permissions_026_a_declared_remote_caller_without_provenance_fails_closed(provenance):[email protected]("bound_session", [False, True])+def test_permissions_026_a_declared_remote_caller_without_provenance_fails_closed(provenance, bound_session):"""PERMISSIONS-026: unusable provenance is anonymous remote, never local Owner."""env = _caller_env("editor")+ if not bound_session:+ env.pop(AVIBE_SESSION_ID_ENV, None)if provenance == "missing":env.pop(AVIBE_CALLER_RESOURCE_CONTEXT_ENV)elif provenance == "malformed":@@ -230,6 +237,22 @@ def test_permissions_026_a_personal_pairing_admits_a_snapshot_without_organizatiassert authority.organization_id is None+def test_permissions_026_unbound_background_editor_cannot_become_local_owner(invoke, monkeypatch, capsys):+ from core.caller_context import background_command_env++ env = background_command_env(+ session_id=None,+ source="scheduled_task",+ metadata={"resource_user_context": _snapshot("editor")},+ run_id="run_background",+ )+ assert AVIBE_SESSION_ID_ENV not in env+ # A forbidden command is refused by the real entry point before any restart.+ monkeypatch.setattr(cli, "cmd_restart", lambda *_a, **_kw: pytest.fail("must not restart"))+ assert invoke(["restart"], caller={key: value for key, value in env.items() if key in CALLER_CONTEXT_ENV_NAMES}) == 1+ assert _refusal(capsys)["code"] == "instance_access_forbidden"++@pytest.mark.parametrize("mismatch", ["instance_id", "instance_kind", "reconciling"])def test_permissions_026_a_snapshot_from_another_pairing_is_anonymous_remote(mismatch):"""PERMISSIONS-026: claims that no longer describe this installation carry no role.diff --git a/tests/test_background_command_caller_context.py b/tests/test_background_command_caller_context.pynew file mode 100644index 000000000..9478bf546--- /dev/null+++ b/tests/test_background_command_caller_context.py@@ -0,0 +1,171 @@+"""Real supervised children must not borrow the service's caller identity.++All child output is synthetic, allowlisted context. Vault writes below use an+isolated database with dummy sealed envelopes, never a real credential or grant.+"""++from __future__ import annotations++import asyncio+from datetime import datetime, timedelta, timezone+import json+import os+from pathlib import Path+import shlex+import sys+import subprocess+from types import SimpleNamespace++import pytest+from sqlalchemy import select++from core.caller_context import AVIBE_CALLER_SESSION_PROOF_ENV, CALLER_CONTEXT_ENV_NAMES+from core.scheduled_tasks import TaskExecutionStore+from core.watches import ManagedWatch, ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore+from storage import vault_service+from storage.db import create_sqlite_engine+from storage.models import metadata as schema, vault_requests+from storage.vault_crypto import Sealed+++def _probe_command() -> list[str]:+ # Import the task source explicitly: neither the installed CLI nor a parent+ # PYTHONPATH is evidence about the code being tested.+ root = str(Path(__file__).resolve().parents[1])+ script = f"""+import json, os, sys+from types import SimpleNamespace+sys.path.insert(0, {root!r})+from core.caller_context import CALLER_CONTEXT_ENV_NAMES, AVIBE_CALLER_SESSION_PROOF_ENV+from vibe.cli import _vault_cli_delivery_context+requester, delivery, session = _vault_cli_delivery_context(SimpleNamespace(), mode="run")+keys = CALLER_CONTEXT_ENV_NAMES | {{AVIBE_CALLER_SESSION_PROOF_ENV,+ "AVIBE_WATCH_ID", "AVIBE_WATCH_LAST_DELIVERY", "COMMAND_CONFIG_PROBE"}}+print(json.dumps({{"requester": requester, "delivery": delivery, "session": session,+ "context": {{key: os.environ[key] for key in keys if key in os.environ}},+ "has_path": bool(os.environ.get("PATH"))}}, ensure_ascii=False))+"""+ return [sys.executable, "-c", script]+++def _contaminate_parent(monkeypatch) -> None:+ for key in CALLER_CONTEXT_ENV_NAMES:+ monkeypatch.setenv(key, "stale-service-caller")+ monkeypatch.setenv("AVIBE_SESSION_ID", "ses_unrelated")+ monkeypatch.setenv("AVIBE_CALLER_REMOTE", "1")+ monkeypatch.setenv("AVIBE_CALLER_RESOURCE_CONTEXT", '{"sub":"wrong-owner"}')+ monkeypatch.setenv(AVIBE_CALLER_SESSION_PROOF_ENV, "stale-proof")+++def _watch(tmp_path, *, session_id, shell=False, metadata=None):+ command = _probe_command()+ watch = ManagedWatch(+ id="wat_context",+ name="会话归属回归",+ session_key="slack::channel::legacy",+ session_id=session_id,+ command=[] if shell else command,+ shell_command=(subprocess.list2cmdline(command) if os.name == "nt" else shlex.join(command)) if shell else None,+ cwd=str(tmp_path),+ metadata=metadata or {},+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=ManagedWatchStore(tmp_path / "watches.json"),+ request_store=TaskExecutionStore(tmp_path / "requests"),+ runtime_store=WatchRuntimeStateStore(tmp_path / "runtime.json"),+ )+ return service, watch++[email protected]("contaminated", [False, True])[email protected]("shell", [False, True])[email protected]("session_id", ["ses_watch_owner", None])+def test_hfr_486_watch_child_vault_callback_uses_only_current_binding(+ tmp_path, monkeypatch, contaminated, shell, session_id+):+ """HFR-486: real Watch -> supervisor -> CLI -> request expiry -> callback."""+ if contaminated:+ _contaminate_parent(monkeypatch)+ monkeypatch.setenv("COMMAND_CONFIG_PROBE", "preserve-普通配置")+ service, watch = _watch(+ tmp_path, session_id=session_id, shell=shell,+ metadata={+ "created_by": {"caller": {"session_id": "ses_old_creator"}},+ "delivered_reports": 3,+ },+ )+ result = asyncio.run(service._run_cycle(watch, timeout_seconds=30))+ assert result.exit_code == 0, result.stderr+ child = json.loads(result.stdout)+ assert child["session"] == session_id+ assert child["has_path"]+ assert child["context"] == {+ **({"AVIBE_SESSION_ID": session_id} if session_id else {}),+ "AVIBE_CALLER_SOURCE": "watch",+ "AVIBE_WATCH_ID": watch.id,+ "AVIBE_WATCH_LAST_DELIVERY": "3",+ "COMMAND_CONFIG_PROBE": "preserve-普通配置",+ }+ assert child["requester"].get("session_id") == session_id+ assert child["delivery"].get("session_id") == session_id++ engine = create_sqlite_engine(tmp_path / "vault.sqlite")+ schema.create_all(engine)+ try:+ with engine.begin() as conn:+ vault_service.create_secret(+ conn, name="TEST_APPROVAL",+ sealed=Sealed(ciphertext="dummy", nonce="dummy", wrap_meta="dummy"),+ protection="protected",+ )+ request = vault_service.create_access_request(+ conn, "TEST_APPROVAL", requester=child["requester"], delivery=child["delivery"],+ )+ conn.execute(+ vault_requests.update().where(vault_requests.c.id == request["id"]).values(+ expires_at=(datetime.now(timezone.utc) - timedelta(minutes=1)).isoformat()+ )+ )+ expired = vault_service._load_request_row(conn, request["id"])+ assert expired["status"] == "expired"+ row = dict(conn.execute(+ select(vault_requests).where(vault_requests.c.id == request["id"])+ ).mappings().one())+ callback = vault_service.resolve_request_callback(row)+ if session_id:+ assert callback is not None+ assert callback.session_id == session_id+ assert "expired" in callback.message+ else:+ assert callback is None+ finally:+ engine.dispose()+++def test_hfr_486_retargeted_watch_uses_the_new_binding_next_cycle(tmp_path, monkeypatch):+ _contaminate_parent(monkeypatch)+ service, watch = _watch(tmp_path, session_id="ses_first")+ for target in ("ses_first", "ses_second", None):+ watch.session_id = target+ result = asyncio.run(service._run_cycle(watch, timeout_seconds=30))+ assert result.exit_code == 0, result.stderr+ assert json.loads(result.stdout)["session"] == target++[email protected]("session_id", ["ses_remote", None])+def test_hfr_486_watch_carries_definition_authority_not_service_authority(tmp_path, monkeypatch, session_id):+ _contaminate_parent(monkeypatch)+ # The runner carries stored provenance; ordinary admission, not this helper,+ # owns whether that snapshot is valid. Exercise those consumers separately.+ snapshot = {"sub": "definition-editor", "vibe_instance_role": "editor"}+ service, watch = _watch(+ tmp_path, session_id=session_id, metadata={"resource_user_context": snapshot},+ )+ result = asyncio.run(service._run_cycle(watch, timeout_seconds=30))+ assert result.exit_code == 0, result.stderr+ child = json.loads(result.stdout)+ assert child["session"] == session_id+ assert child["context"]["AVIBE_CALLER_REMOTE"] == "1"+ assert json.loads(child["context"]["AVIBE_CALLER_RESOURCE_CONTEXT"]) == snapshot+ assert AVIBE_CALLER_SESSION_PROOF_ENV not in child["context"]diff --git a/tests/test_caller_context.py b/tests/test_caller_context.pyindex 178bdf778..431529313 100644--- a/tests/test_caller_context.py+++ b/tests/test_caller_context.py@@ -28,6 +28,21 @@ def test_caller_context_from_env_requires_session_id() -> None:assert caller_context_from_env({}) is None+def test_independent_environment_drops_proof_without_making_it_persistable() -> None:+ from core.caller_context import (+ AVIBE_CALLER_SESSION_PROOF_ENV,+ CALLER_CONTEXT_ENV_NAMES,+ environment_without_caller_context,+ validated_caller_env_snapshot,+ )++ env = {key: "old" for key in CALLER_CONTEXT_ENV_NAMES}+ env.update({AVIBE_CALLER_SESSION_PROOF_ENV: "transient", "KEEP": "ordinary"})+ assert environment_without_caller_context(env) == {"KEEP": "ordinary"}+ assert AVIBE_CALLER_SESSION_PROOF_ENV not in validated_caller_env_snapshot(env)+ assert env[AVIBE_CALLER_SESSION_PROOF_ENV] == "transient"++def test_caller_context_from_env_round_trips_metadata_and_env() -> None:context = caller_context_from_env({diff --git a/tests/test_command_runner.py b/tests/test_command_runner.pyindex d200dbcb2..28aaa00c2 100644--- a/tests/test_command_runner.py+++ b/tests/test_command_runner.py@@ -569,3 +569,23 @@ async def test_remove_env_deletes_inherited_and_extra_keys(tmp_path: Path) -> Noassert result.exit_code == 0assert result.stdout.splitlines() == ["False", "present"]+++async def test_explicit_environment_replaces_parent_without_losing_supervision(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("PARENT_ONLY", "must not leak")+ supplied = {"CHILD_ONLY": "present"}+ spawned = []+ result = await run_supervised_command(+ command=[sys.executable, "-c",+ "import os; print(os.environ.get('PARENT_ONLY')); print(os.environ.get('CHILD_ONLY'))"],+ cwd=str(tmp_path),+ timeout_seconds=10,+ label="explicit environment",+ env=supplied,+ on_spawn=lambda pid, identity: spawned.append((pid, identity)),+ )+ assert result.exit_code == 0+ assert result.stdout.splitlines() == ["None", "present"]+ assert supplied == {"CHILD_ONLY": "present"}+ assert spawned[0][1] is not None+ assert spawned[0][1].pid == spawned[0][0]diff --git a/tests/test_scheduled_command_task_integration.py b/tests/test_scheduled_command_task_integration.pyindex d8d073c35..b9db85928 100644--- a/tests/test_scheduled_command_task_integration.py+++ b/tests/test_scheduled_command_task_integration.py@@ -11,10 +11,14 @@ Hermetic: state, definition store, and the fallback spawn cwd all land in `tmp_p"""import asyncio+import jsonfrom pathlib import Path+import sysfrom types import SimpleNamespacefrom unittest.mock import patch+import pytest+import config.paths as pathsfrom core.caller_context import (AVIBE_CALLER_BACKEND_ENV,@@ -309,3 +313,65 @@ def test_cli_created_argv_command_task_runs(assert run["status"] == "succeeded", f"the argv run failed: {run['error']!r}"assert marker.read_text().strip() == "argv"++[email protected]("bound_session", [False, True])+def test_sct_062_command_fire_replaces_service_caller_with_definition_binding(+ tmp_path: Path, monkeypatch, bound_session+) -> None:+ """SCT-062: real claimed Run -> supervisor -> Vault CLI context."""+ from core.caller_context import AVIBE_CALLER_SESSION_PROOF_ENV+ from storage.agent_session_rows import create_agent_session_row+ from storage.db import create_sqlite_engine++ _isolate(tmp_path, monkeypatch)+ session_id = None+ if bound_session:+ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ session_id = create_agent_session_row(+ conn, scope_id=None, session_anchor="command-context",+ agent_backend="codex", agent_variant="codex",+ native_session_id="test-native", workdir=str(tmp_path),+ require_workdir=False,+ )+ finally:+ engine.dispose()+ root = str(Path(__file__).resolve().parents[1])+ script = f"""+import json, os, sys+from types import SimpleNamespace+sys.path.insert(0, {root!r})+from core.caller_context import CALLER_CONTEXT_ENV_NAMES, AVIBE_CALLER_SESSION_PROOF_ENV+from vibe.cli import _vault_cli_delivery_context+keys = CALLER_CONTEXT_ENV_NAMES | {{AVIBE_CALLER_SESSION_PROOF_ENV}}+print(json.dumps({{"context": {{key: os.environ[key] for key in keys if key in os.environ}},+ "vault": _vault_cli_delivery_context(SimpleNamespace(), mode="run")}}))+"""+ store = _store(tmp_path)+ task = store.add_task(+ session_key="", session_id=session_id, prompt="", schedule_type="cron",+ cron="0 * * * *", timezone_name="UTC", cwd=str(tmp_path),+ command=[sys.executable, "-c", script],+ metadata={+ "on_failure": "agent" if bound_session else "none",+ "created_by": {"caller": {"session_id": "ses_original_creator"}},+ },+ )+ for key in (*_CALLER_ENV_VARS, AVIBE_CALLER_SESSION_PROOF_ENV):+ monkeypatch.setenv(key, "stale-service-caller")+ calls = []+ run = _fire(_service(tmp_path, calls), task)+ assert run["status"] == "succeeded", run["error"]+ child = json.loads(run["stdout"])+ assert child["context"] == {+ **({"AVIBE_SESSION_ID": session_id} if session_id else {}),+ "AVIBE_CALLER_SOURCE": "scheduled_task",+ "AVIBE_RUN_ID": run["id"],+ }+ requester, delivery, actual_session = child["vault"]+ assert actual_session == session_id+ assert requester.get("session_id") == session_id+ assert delivery.get("session_id") == session_id+ assert calls == []diff --git a/vibe/cli.py b/vibe/cli.pyindex 1b6e1e0fa..06961613e 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -51,7 +51,7 @@ from core.scheduled_tasks import (from core.caller_context import (caller_context_from_env,caller_resource_user_context,- env_declares_remote_caller,+ caller_resource_user_context_from_env,)from core.command_runner import command_line_previewfrom core.install_integrity import verify_python_environment, verify_site_packages@@ -18555,9 +18555,8 @@ def _cli_invocation_authority(env: Optional[Mapping[str, str]] = None):)from vibe.authorization import AuthorizationContext- source = os.environ if env is None else env- snapshot = caller_resource_user_context(caller_context_from_env(source))- if snapshot is None and not env_declares_remote_caller(source):+ snapshot = caller_resource_user_context_from_env(env)+ if snapshot is None:return Nonecontext = resource_user_context_from_metadata({RESOURCE_USER_CONTEXT_METADATA_KEY: snapshot})return AuthorizationContext(is_remote=True) if context is None else context