Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

Simplify Harness agent run scope semantics (#717)

Call White7d55dc2081c6
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index fde2a35ab..3ed2e78e6 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -149,6 +149,26 @@ def parse_session_key(value: str) -> ParsedSessionKey:
)
+def parse_scope_id(value: str) -> ParsedSessionKey:
+ raw = (value or "").strip()
+ parts = raw.split("::") if raw else []
+ if len(parts) != 3:
+ raise ValueError("scope id must be '<platform>::<scope_type>::<native_id>'")
+
+ platform, scope_type, native_id = parts
+ if not platform or not scope_type or not native_id:
+ raise ValueError("scope id platform, scope type, and native id are required")
+ if scope_type not in {"channel", "user", "project"}:
+ raise ValueError("scope id scope type must be 'channel', 'user', or 'project'")
+
+ return ParsedSessionKey(
+ platform=platform,
+ scope_type=scope_type,
+ scope_id=native_id,
+ thread_id=None,
+ )
+
+
def session_anchor_for_target(target: ParsedSessionKey) -> str:
anchor_id = target.thread_id or target.scope_id
return f"{target.platform}_{anchor_id}"
@@ -317,6 +337,7 @@ class ScheduledTask:
session_id: Optional[str] = None
post_to: Optional[str] = None
deliver_key: Optional[str] = None
+ cwd: Optional[str] = None
cron: Optional[str] = None
run_at: Optional[str] = None
timezone: str = "UTC"
@@ -343,6 +364,7 @@ class ScheduledTask:
session_id=(str(payload["session_id"]).strip() if payload.get("session_id") else None),
post_to=payload.get("post_to"),
deliver_key=payload.get("deliver_key"),
+ cwd=(str(payload["cwd"]).strip() if payload.get("cwd") else None) or None,
cron=payload.get("cron"),
run_at=payload.get("run_at"),
timezone=str(payload.get("timezone") or "UTC"),
@@ -622,6 +644,7 @@ class ScheduledTaskStore:
session_policy: Optional[str] = None,
post_to: Optional[str] = None,
deliver_key: Optional[str] = None,
+ cwd: Optional[str] = None,
cron: Optional[str] = None,
run_at: Optional[str] = None,
timezone_name: str,
@@ -638,6 +661,7 @@ class ScheduledTaskStore:
session_policy=session_policy or ("existing" if session_id or session_key else None),
post_to=post_to,
deliver_key=deliver_key,
+ cwd=cwd,
cron=cron,
run_at=run_at,
timezone=timezone_name,
@@ -681,6 +705,9 @@ class ScheduledTaskStore:
session_id: Optional[str] = None,
agent_name: Optional[str] = None,
session_policy: Optional[str] = None,
+ cwd: Optional[str] = None,
+ update_cwd: bool = False,
+ metadata: Optional[dict[str, Any]] = None,
) -> ScheduledTask:
task = self._tasks[task_id]
task.name = name
@@ -694,9 +721,13 @@ class ScheduledTaskStore:
task.session_policy = session_policy
task.post_to = post_to
task.deliver_key = deliver_key
+ if update_cwd:
+ task.cwd = cwd
task.cron = cron
task.run_at = run_at
task.timezone = timezone_name
+ if metadata is not None:
+ task.metadata = dict(metadata)
task.updated_at = _utc_now_iso()
if self._sqlite is not None:
self._sqlite.upsert_scheduled_task(task.to_dict())
@@ -809,6 +840,7 @@ class TaskExecutionStore:
prompt=task.prompt,
agent_name=task.agent_name,
session_policy=task.session_policy,
+ metadata=task.metadata,
)
def enqueue_definition_run(
@@ -826,6 +858,7 @@ class TaskExecutionStore:
session_policy: Optional[str],
source_actor: Optional[str] = None,
parent_run_id: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
) -> TaskExecutionRequest:
return self.enqueue(
TaskExecutionRequest(
@@ -843,6 +876,7 @@ class TaskExecutionStore:
parent_run_id=parent_run_id,
agent_name=agent_name,
session_policy=session_policy,
+ metadata=dict(metadata or {}),
)
)
@@ -861,6 +895,7 @@ class TaskExecutionStore:
source_kind: str = "cli",
source_actor: Optional[str] = None,
parent_run_id: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
) -> TaskExecutionRequest:
return self.enqueue(
TaskExecutionRequest(
@@ -878,6 +913,7 @@ class TaskExecutionStore:
parent_run_id=parent_run_id,
agent_name=agent_name,
session_policy=session_policy,
+ metadata=dict(metadata or {}),
)
)
@@ -899,6 +935,7 @@ class TaskExecutionStore:
source_actor: Optional[str] = None,
parent_run_id: Optional[str] = None,
callback_session_id: Optional[str] = None,
+ callback_active: bool = True,
metadata: Optional[dict[str, Any]] = None,
) -> TaskExecutionRequest:
return self.enqueue(
@@ -915,7 +952,7 @@ class TaskExecutionStore:
source_actor=source_actor,
parent_run_id=parent_run_id,
callback_session_id=callback_session_id,
- callback_status="pending" if callback_session_id else None,
+ callback_status="pending" if callback_session_id and callback_active else None,
agent_name=agent_name,
agent_id=agent_id,
agent_backend=agent_backend,
@@ -1013,6 +1050,41 @@ class TaskExecutionStore:
tmp_path.replace(path)
return
+ def mark_callback_pending(self, run_id: str) -> None:
+ if self._sqlite is not None:
+ self._sqlite.mark_callback_pending(run_id)
+ return
+ now = _utc_now_iso()
+ for state in ("pending", "processing", "completed"):
+ path = self._request_path(run_id, state=state)
+ if not path.exists():
+ continue
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ payload = {"id": run_id}
+ if not isinstance(payload, dict):
+ payload = {"id": run_id}
+ payload.update(
+ {
+ "callback_status": "pending",
+ "callback_error": None,
+ "callback_completed_at": None,
+ "updated_at": now,
+ }
+ )
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ dir=path.parent,
+ suffix=".tmp",
+ delete=False,
+ encoding="utf-8",
+ ) as handle:
+ json.dump(payload, handle, indent=2)
+ tmp_path = Path(handle.name)
+ tmp_path.replace(path)
+ return
+
def list_runs_page(
self,
*,
@@ -1659,6 +1731,8 @@ class ScheduledTaskService:
session_id = self._reserve_runtime_session(
agent_name=request.agent_name,
deliver_key=request.deliver_key,
+ metadata=request.metadata,
+ workdir=request.metadata.get("session_workdir") if isinstance(request.metadata, dict) else None,
)
session_key = ""
elif not (request.session_id or request.session_key):
@@ -1746,6 +1820,8 @@ class ScheduledTaskService:
session_id = self._reserve_runtime_session(
agent_name=task.agent_name,
deliver_key=task.deliver_key,
+ metadata=task.metadata,
+ workdir=task.cwd,
)
session_key = ""
error = await self._execute_request(
@@ -1861,19 +1937,33 @@ class ScheduledTaskService:
return AgentRunExecutionResult(error=str(result), complete_on_return=True)
return AgentRunExecutionResult(error=None, complete_on_return=False)
- def _reserve_runtime_session(self, *, agent_name: Optional[str], deliver_key: Optional[str]) -> str:
- if not deliver_key:
- raise ValueError("session creation requires deliver_key")
+ def _reserve_runtime_session(
+ self,
+ *,
+ agent_name: Optional[str],
+ deliver_key: Optional[str],
+ metadata: Optional[dict[str, Any]] = None,
+ workdir: Optional[str] = None,
+ ) -> str:
+ scope_id = ""
+ legacy_delivery_target: Optional[ParsedSessionKey] = None
+ if isinstance(metadata, dict):
+ scope_id = str(metadata.get("session_scope_id") or "").strip()
+ if not scope_id:
+ legacy_delivery_target = parse_session_key(str(deliver_key or "").strip()) if deliver_key else None
+ scope_id = legacy_delivery_target.session_scope if legacy_delivery_target is not None else ""
+ if not scope_id:
+ raise ValueError("session creation requires scope_id")
from config import paths as config_paths
from core.vibe_agents import VibeAgentStore
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.sessions_service import SQLiteSessionsService
- target = parse_session_key(deliver_key)
+ target = parse_scope_id(scope_id)
ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(config_paths.get_state_dir()))
agent_store = VibeAgentStore()
try:
- scope_target = self._resolve_scope_agent_target(deliver_key) if not agent_name else _ScopeAgentTarget(None)
+ scope_target = self._resolve_scope_agent_target(scope_id) if not agent_name else _ScopeAgentTarget(None)
resolved_agent_name = agent_name or scope_target.agent_name
agent = agent_store.require_enabled(resolved_agent_name) if resolved_agent_name else agent_store.get_default_agent()
finally:
@@ -1886,11 +1976,12 @@ class ScheduledTaskService:
session_id = service.reserve_agent_session(
scope_key=target.session_scope,
agent_backend=agent_backend,
- session_anchor=session_anchor_for_target(target),
+ session_anchor=f"{session_anchor_for_target(target)}:runtime_{uuid4().hex[:12]}",
agent_id=agent.id if agent else None,
agent_name=agent.name if agent else None,
model=agent.model if agent else None,
reasoning_effort=agent.reasoning_effort if agent else None,
+ workdir=workdir,
)
finally:
service.close()
@@ -1900,9 +1991,12 @@ class ScheduledTaskService:
def _resolve_scope_agent_target(self, deliver_key: str) -> "_ScopeAgentTarget":
try:
- target = parse_session_key(deliver_key)
+ target = parse_scope_id(deliver_key)
except ValueError:
- return _ScopeAgentTarget(None)
+ try:
+ target = parse_session_key(deliver_key)
+ except ValueError:
+ return _ScopeAgentTarget(None)
from config import paths as config_paths
from storage.settings_service import make_scope_id
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 09de12b34..67c05e530 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -102,6 +102,7 @@ def reserve_forked_session(
agent_name: Optional[str] = None,
model: Optional[str] = None,
reasoning_effort: Optional[str] = None,
+ scope_id: Optional[str] = None,
trim_latest_running_turn: bool = False,
native_turn_started: bool = False,
db_path: Optional[Path] = None,
@@ -183,13 +184,22 @@ def reserve_forked_session(
target_backend = override_agent.backend if override_agent else source_backend
target_variant = target_backend if override_agent else str(row["agent_variant"] or target_backend)
now = utc_now_iso()
- target_anchor = _fork_session_anchor(row["session_anchor"], source_session_id=str(row["id"]), now=now)
target_model = _clean_optional(model) if model is not None else row["model"]
target_effort = (
_clean_optional(reasoning_effort)
if reasoning_effort is not None
else row["reasoning_effort"]
)
+ explicit_scope_id = _clean_optional(scope_id) if scope_id is not None else None
+ target_scope_id = explicit_scope_id or row["scope_id"]
+ if explicit_scope_id or target_scope_id != row["scope_id"]:
+ target_anchor = _fork_session_anchor(
+ _anchor_for_scope_id(target_scope_id),
+ source_session_id=str(row["id"]),
+ now=now,
+ )
+ else:
+ target_anchor = _fork_session_anchor(row["session_anchor"], source_session_id=str(row["id"]), now=now)
source_title = str(row["title"] or "").strip()
target_title = _forked_session_title(source_title, title_lang)
@@ -216,9 +226,14 @@ def reserve_forked_session(
metadata["fork_opencode_fork_empty_history"] = True
if opencode_boundary_from_active_run:
metadata["fork_opencode_boundary_from_active_run"] = True
+ if target_scope_id != row["scope_id"]:
+ metadata["fork_target_scope_id"] = target_scope_id
+ metadata["legacy_scope_key"] = target_scope_id
+ metadata.pop("private_agent_run", None)
+ metadata.pop("no_delivery", None)
session_id = create_agent_session_row(
conn,
- scope_id=row["scope_id"],
+ scope_id=target_scope_id,
# Keep IM delivery stable while satisfying the per-scope anchor
# uniqueness invariant. resolve_session_id_target strips the
# suffix after ":" when deriving the IM thread id.
@@ -544,3 +559,16 @@ def _fork_session_anchor(value: Any, *, source_session_id: str, now: str) -> Opt
return None
suffix = "".join(ch for ch in f"{source_session_id}_{now}" if ch.isalnum())
return f"{anchor}:fork_{suffix}_{secrets.token_hex(3)}"
+
+
+def _anchor_for_scope_id(scope_id: Any) -> Optional[str]:
+ value = _clean_optional(scope_id)
+ if not value:
+ return None
+ try:
+ platform, scope_type, native_id = value.split("::", 2)
+ except ValueError:
+ return None
+ if not (platform and scope_type and native_id):
+ return None
+ return f"{platform}_{native_id}"
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index c10ba8cac..b74d4a101 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -174,9 +174,9 @@ Useful Harness queries include schema discovery, current session lookup, existin
| --- | --- |
| Time trigger | `vibe task add` |
| External signal trigger | `vibe watch add` |
-| Independent Agent delegation | `vibe agent run --create-session` |
+| Independent Agent delegation | `vibe agent run --agent <agent-name>` |
| Same-session follow-up | `vibe agent run --session-id ...` |
-| Branch from existing Session context | `vibe agent run --fork-session ...` |
+| Branch from current Session context | `vibe agent run --fork-self ...` |
| State/history inspection | `vibe data query`, `vibe runs list`, `vibe runs show` |
| Recurring specialist workflow | `vibe agent create/update` plus tasks, watches, or runs |
@@ -184,11 +184,11 @@ Useful Harness queries include schema discovery, current session lookup, existin
`vibe watch add` creates a managed monitor, usually backed by a small script or command, for any observable condition that must be watched until true: product signals, business events, files, logs, CI/reviews/deploys, service health, data freshness, and similar signals.
-Use `vibe agent run --async ...` when one Agent delegates work to another Session and the final result text should return to this caller Session as a follow-up Agent message. Avibe injects this Session as the default async callback target. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later.
+Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. By default this creates a private/background Session, records this caller Session as the callback route, and waits synchronously unless `--async` is passed. Add `--same-scope` when the new Session should live under the same Workbench project or IM scope as the caller. Add `--scope-id <scopes.id>` only when placing the new Session in a specific existing scope.
-Use `vibe agent run --fork-session <source-session-id> --message ...` when work should branch from an existing Session's native backend context without mutating that source Session. Forks keep the source Session backend; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same. Do not combine `--fork-session` with `--session-id`, `--create-session`, `--deliver-key`, or `--post-to`.
+Use `vibe agent run --fork-self --message ...` when work should branch from this current Session's native backend context without mutating it. Use `--fork-session <source-session-id>` only when branching from a different explicit Session. Forks keep the source Session backend, scope, and cwd by default; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same.
-`--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel. For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--prefix "..."` for the follow-up instruction prepended before waiter stdout.
+For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--prefix "..."` for the follow-up instruction prepended before waiter stdout. `--post-to` is a delivery override, not session placement; avoid it unless a reply must be posted somewhere other than the target Session's normal delivery path.
Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`.
@@ -201,11 +201,12 @@ The table below is generated from currently enabled Agents at prompt-injection t
Rules:
- All Agents listed in the generated table are enabled. Use the `Agent Name` value exactly as listed in shell commands such as `vibe agent show <agent-name>` and `vibe agent run --agent <agent-name> ...`.
-- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. `--create-session` creates a separate Session for the target Agent.
-- `--fork-session <id>` creates a new Agent Session from that source Session's native backend context; use it for alternate paths that need the source context but should not mutate the source Session.
-- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --create-session --message ...`.
+- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate private/background Session for the target Agent.
+- `--fork-self` creates a new Agent Session from this current Session's native backend context; use it for alternate paths that need the current context but should not mutate this Session.
+- `--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context.
+- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --message ...`.
- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only to continue that same Session. Reuse the current session id only with Agents whose `Backend` matches `{current_agent_backend}`; otherwise use `--create-session`.
-- With `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides, and only when the requested Agent backend matches the source Session backend.
+- With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides, and only when the requested Agent backend matches the source Session backend.
- `--async` changes waiting behavior, not session identity: synchronous waits for the result; async runs in the background and is inspected later with `vibe runs`.
- Create or update Agents only when it captures a reusable role, reduces repeated prompting, or makes a long-running Harness more reliable.
diff --git a/core/watches.py b/core/watches.py
index a945c3f71..3983adf5a 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -275,6 +275,7 @@ class ManagedWatchStore:
agent_name: Optional[str] = None,
session_policy: Optional[str] = None,
message: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
) -> ManagedWatch:
watch = self._watches[watch_id]
watch.name = name
@@ -296,6 +297,8 @@ class ManagedWatchStore:
watch.retry_delay_seconds = retry_delay_seconds
watch.post_to = post_to
watch.deliver_key = deliver_key
+ if metadata is not None:
+ watch.metadata = dict(metadata)
watch.updated_at = _utc_now_iso()
if self._sqlite is not None:
self._sqlite.upsert_watch(watch.to_dict())
@@ -728,6 +731,7 @@ class ManagedWatchService:
run_type="watch",
definition_id=watch.id,
source_kind="watch",
+ metadata=watch.metadata,
)
def _enqueue_failure_hook(self, watch: ManagedWatch, *, exit_code: int, error_text: str) -> None:
diff --git a/docs/plans/agent-run-scope-semantics.md b/docs/plans/agent-run-scope-semantics.md
new file mode 100644
index 000000000..6be2e2a78
--- /dev/null
+++ b/docs/plans/agent-run-scope-semantics.md
@@ -0,0 +1,105 @@
+# Agent Run Scope Semantics
+
+## Problem
+
+The Harness CLI used to expose backend and transport details directly to
+agents. In particular, `vibe agent run`, `vibe task`, and `vibe watch` relied on
+explicit session ids, delivery keys, and post targets even when Avibe already
+knows the calling Agent Session through `AVIBE_SESSION_ID`.
+
+That made agents carry routing details in prompts instead of using the runtime
+context as a first-class API.
+
+## Principles
+
+- `AVIBE_SESSION_ID` identifies the caller session.
+- Callback routing is a run-level completion policy, not a session-level
+ default. Synchronous runs should still record the callback route so a future
+ long-running sync turn can detach into async without losing its return path.
+- Scope placement is a session-level decision. It decides where a newly-created
+ session lives: a private/background scope, the caller/source scope, or a
+ specific `scopes.id`.
+- Message delivery overrides are not scope placement. `post-to` remains a reply
+ delivery override; it does not move a session.
+- `deliver-key` is legacy transport syntax and should leave the agent-facing
+ CLI surface. New commands should use `--scope-id` or `--same-scope`.
+
+## `vibe agent run` Defaults
+
+When an agent runs another agent with no explicit target:
+
+```bash
+vibe agent run --agent claude --message "Review this patch"
+```
+
+Avibe treats it as:
+
+- create a new private/background session;
+- use the caller shell cwd as the new session cwd;
+- record callback route to the caller session when `AVIBE_SESSION_ID` exists;
+- keep the run synchronous unless `--async` is explicitly passed.
+
+The async-by-default proposal is intentionally left as a follow-up. It changes
+the waiting contract of every existing caller and should land separately with a
+focused migration.
+
+## New Target And Scope Parameters
+
+| Parameter | Meaning |
+| --- | --- |
+| `--fork-self` | Fork the current caller session without passing its id. Requires `AVIBE_SESSION_ID`. |
+| `--fork-session <session-id>` | Fork the specified source session. |
+| `--same-scope` | Place a newly-created session in the caller/source session's scope. |
+| `--scope-id <scopes.id>` | Place a newly-created session in the exact scope row. |
+| no scope parameter on create | Create a private/background session. |
+
+Forks inherit the source session's scope and cwd by default. `--same-scope` is
+therefore redundant but acceptable for fork commands. `--scope-id` may be used
+to fork into a different scope.
+
+## CWD Rules
+
+| Operation | Default cwd |
+| --- | --- |
+| create private/background session | caller shell cwd |
+| create with `--same-scope` | caller shell cwd |
+| create with `--scope-id` | caller shell cwd |
+| fork self/session | source session cwd |
+| continue existing session | existing session cwd |
+| explicit `--cwd` | wins for blank create only |
+
+## Callback Route Rules
+
+All `vibe agent run` invocations resolve a callback route:
+
+- explicit `--callback-session-id` wins;
+- `--no-callback` records an intentional no-callback policy;
+- otherwise, `AVIBE_SESSION_ID` becomes the callback route when available.
+
+For async runs, the callback route is used when the run completes. For sync
+runs, the route is only recorded for future detach-to-async behavior.
+
+## Other CLI Defaults
+
+- `vibe runs list` remains global by default.
+- `vibe runs list --current-session` filters to `AVIBE_SESSION_ID`.
+- `vibe runs show` may default to `AVIBE_RUN_ID`.
+- `vibe runs cancel` stays explicit; no `--current-run` shortcut in this batch.
+- Single-object session commands may default object id from `AVIBE_SESSION_ID`.
+- `vibe task add` / `vibe watch add` default their target session to
+ `AVIBE_SESSION_ID` when they continue an existing session.
+- When a task or watch creates sessions, agents should use `--same-scope` or
+ `--scope-id <scopes.id>`. The selected placement scope is stored in definition
+ metadata as `session_scope_id`, so future `create-session-per-run` triggers
+ can create the session in the right Workbench project or IM scope.
+- `vibe task add` and `vibe watch add` snapshot the caller shell cwd when
+ `--cwd` is omitted. That cwd is reused when the definition later creates
+ sessions.
+
+## Migration
+
+This batch removes `deliver-key` from recommended agent-facing help, prompt
+injection, and examples. Internal persistence can keep legacy field names until
+a later database cleanup. The CLI may continue accepting hidden legacy
+`--deliver-key` for compatibility, but new code paths write placement through
+`scope_id` semantics.
diff --git a/storage/background.py b/storage/background.py
index c610a2560..ccc027986 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -958,6 +958,17 @@ class SQLiteBackgroundTaskStore:
with self.engine.begin() as conn:
conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+ def mark_callback_pending(self, run_id: str, *, updated_at: Optional[str] = None) -> None:
+ now = updated_at or _utc_now_iso()
+ values: dict[str, Any] = {
+ "callback_status": "pending",
+ "callback_error": None,
+ "callback_completed_at": None,
+ "updated_at": now,
+ }
+ with self.engine.begin() as conn:
+ conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+
def mark_run_queued_from_running(
self,
run_id: str,
@@ -1127,7 +1138,7 @@ class SQLiteBackgroundTaskStore:
"command_json": None,
"shell_command": None,
"prefix": None,
- "cwd": None,
+ "cwd": payload.get("cwd"),
"mode": None,
"timeout_seconds": None,
"lifetime_timeout_seconds": None,
@@ -1217,7 +1228,7 @@ class SQLiteBackgroundTaskStore:
"result_payload_json": self._payload_json(payload, "result_payload", "result_payload_json"),
"message_ids_json": self._payload_json(payload, "message_ids", "message_ids_json"),
"callback_session_id": payload.get("callback_session_id"),
- "callback_status": payload.get("callback_status") or ("pending" if payload.get("callback_session_id") else None),
+ "callback_status": payload.get("callback_status"),
"callback_error": payload.get("callback_error"),
"callback_run_id": payload.get("callback_run_id"),
"callback_completed_at": payload.get("callback_completed_at"),
@@ -1250,6 +1261,7 @@ class SQLiteBackgroundTaskStore:
"schedule_type": row["schedule_type"] or "",
"post_to": row["post_to"],
"deliver_key": row["deliver_key"],
+ "cwd": row["cwd"],
"cron": row["cron"],
"run_at": row["run_at"],
"timezone": row["timezone"] or "UTC",
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 18bbca61c..899f76862 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -997,7 +997,7 @@ def _lookup_scope_id(conn: Connection, scope_key: str) -> str | None:
def resolve_scope_from_legacy_key(conn: Connection, scope_key: str, *, now: str) -> str | None:
raw_scope_key = str(scope_key or "")
parts = raw_scope_key.split("::")
- if len(parts) == 3 and parts[1] in {"channel", "user", "platform"}:
+ if len(parts) == 3 and parts[1] in {"channel", "user", "platform", "project"}:
platform, scope_type, native_id = parts
if not platform or not native_id:
return None
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index 00ccb7f88..21d5e71cf 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -19,6 +19,8 @@ import sys
from pathlib import Path
from unittest.mock import patch
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import vibe.cli as cli
@@ -29,6 +31,18 @@ def _parse_agent_run(argv: list[str]):
return parser.parse_args(["agent", "run", *argv])
[email protected](autouse=True)
+def _clear_caller_env(monkeypatch):
+ for key in (
+ "AVIBE_SESSION_ID",
+ "AVIBE_RUN_ID",
+ "AVIBE_CALLER_SOURCE",
+ "AVIBE_CALLER_BACKEND",
+ "AVIBE_NATIVE_SESSION_ID",
+ ):
+ monkeypatch.delenv(key, raising=False)
+
+
_EXPECTED_KEYS = {
"schema_version",
"ok",
@@ -41,6 +55,7 @@ _EXPECTED_KEYS = {
"session_policy",
"session_id",
"deliver_key",
+ "scope_id",
"callback_session_id",
"caller_context",
"callback_notice",
@@ -54,6 +69,7 @@ _EXPECTED_RUN_KEYS_QUEUED = {
"run_type",
"agent_name",
"session_id",
+ "scope_id",
"callback_session_id",
"source_kind",
"source_actor",
@@ -314,7 +330,7 @@ def test_agent_run_async_defaults_callback_from_caller_env(tmp_path: Path, capsy
assert stored["metadata"]["caller_context"]["session_id"] == caller_session["id"]
-def test_agent_run_async_requires_explicit_policy_when_target_is_caller_session(
+def test_agent_run_async_self_target_defaults_to_no_callback(
tmp_path: Path, capsys
) -> None:
from core.services import sessions as sessions_service
@@ -381,22 +397,323 @@ def test_agent_run_async_requires_explicit_policy_when_target_is_caller_session(
):
result = cli.cmd_agent_run(args)
- assert result == 1
- payload = json.loads(capsys.readouterr().err)
- assert payload["code"] == "self_callback_requires_explicit_policy"
- assert "--no-callback" in payload["hint"]
- assert request_store.list_pending() == []
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["callback_session_id"] is None
+ assert payload["callback_notice"]["code"] == "async_self_run_without_callback"
+ stored = request_store.get_run(payload["run_id"])
+ assert stored is not None
+ assert stored["callback_session_id"] is None
+ assert stored["callback_status"] is None
-def test_agent_run_callback_session_requires_async(capsys) -> None:
- args = _parse_agent_run(["--agent", "worker", "--callback-session-id", "ses1", "--message", "hi"])
+def test_agent_run_sync_self_target_detach_defaults_to_no_callback(
+ tmp_path: Path, capsys
+) -> None:
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
- result = cli.cmd_agent_run(args)
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_caller",
+ now="2026-06-10T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-10T00:00:00Z",
+ updated_at="2026-06-10T00:00:00Z",
+ )
+ )
+ caller_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="caller",
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="caller", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(["--session-id", caller_session["id"], "--message", "hi"])
- assert result == 1
+ with (
+ patch.dict(
+ "os.environ",
+ {
+ "AVIBE_SESSION_ID": caller_session["id"],
+ "AVIBE_RUN_ID": "run-parent",
+ "AVIBE_CALLER_SOURCE": "agent_run",
+ "AVIBE_CALLER_BACKEND": "codex",
+ },
+ ),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch(
+ "vibe.cli._wait_for_run_result",
+ return_value={
+ "id": "still-running",
+ "status": "running",
+ "wait_state": "detached",
+ "handoff_reason": "wait_limit_reached",
+ },
+ ),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["callback_session_id"] is None
+ assert payload["callback_notice"]["code"] == "async_self_run_without_callback"
+ assert payload["run"].get("callback_status") is None
+ stored = request_store.get_run(payload["run_id"])
+ assert stored is not None
+ assert stored["callback_session_id"] is None
+ assert stored["callback_status"] is None
+
+
+def test_agent_run_callback_session_records_sync_route(tmp_path: Path, capsys) -> None:
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_callback_sync",
+ now="2026-06-10T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-10T00:00:00Z",
+ updated_at="2026-06-10T00:00:00Z",
+ )
+ )
+ callback_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(["--agent", "worker", "--callback-session-id", callback_session["id"], "--message", "hi"])
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._primary_platform", return_value="slack"),
+ patch("vibe.cli._wait_for_run_result", return_value={"id": "done", "status": "succeeded"}),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
captured = capsys.readouterr()
- payload = json.loads(captured.out or captured.err)
- assert payload["code"] == "callback_requires_async"
+ payload = json.loads(captured.out)
+ assert payload["callback_session_id"] == callback_session["id"]
+ stored = request_store.get_run(payload["run_id"])
+ assert stored is not None
+ assert stored["callback_session_id"] == callback_session["id"]
+ assert stored["callback_status"] is None
+
+
+def test_agent_run_callback_session_records_sync_route_in_sqlite_store(tmp_path: Path, capsys) -> None:
+ from core.services import sessions as sessions_service
+ from sqlalchemy import select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_runs, scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ with create_sqlite_engine(db_path).begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C123",
+ now="2026-06-10T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-10T00:00:00Z",
+ updated_at="2026-06-10T00:00:00Z",
+ )
+ )
+ callback_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )
+
+ args = _parse_agent_run(
+ ["--agent", "worker", "--callback-session-id", callback_session["id"], "--message", "hi"]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli.paths.get_state_dir", return_value=state_home / "state"),
+ patch("vibe.cli._primary_platform", return_value="slack"),
+ patch("vibe.cli._wait_for_run_result", return_value={"id": "done", "status": "succeeded"}),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ with create_sqlite_engine(db_path).connect() as conn:
+ row = conn.execute(
+ select(agent_runs.c.callback_session_id, agent_runs.c.callback_status)
+ .where(agent_runs.c.id == payload["run_id"])
+ .limit(1)
+ ).mappings().one()
+ assert row["callback_session_id"] == callback_session["id"]
+ assert row["callback_status"] is None
+ assert cli.TaskExecutionStore().list_pending_callbacks() == []
+
+
+def test_agent_run_sync_detach_marks_callback_pending(tmp_path: Path, capsys) -> None:
+ from core.services import sessions as sessions_service
+ from sqlalchemy import select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_runs, scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ with create_sqlite_engine(db_path).begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C123",
+ now="2026-06-10T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-10T00:00:00Z",
+ updated_at="2026-06-10T00:00:00Z",
+ )
+ )
+ callback_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )
+
+ args = _parse_agent_run(
+ ["--agent", "worker", "--callback-session-id", callback_session["id"], "--message", "hi"]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli.paths.get_state_dir", return_value=state_home / "state"),
+ patch("vibe.cli._primary_platform", return_value="slack"),
+ patch(
+ "vibe.cli._wait_for_run_result",
+ return_value={
+ "id": "still-running",
+ "status": "running",
+ "wait_state": "detached",
+ "handoff_reason": "wait_limit_reached",
+ },
+ ),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["run"]["callback_status"] == "pending"
+ with create_sqlite_engine(db_path).connect() as conn:
+ row = conn.execute(
+ select(agent_runs.c.callback_status, agent_runs.c.callback_completed_at)
+ .where(agent_runs.c.id == payload["run_id"])
+ .limit(1)
+ ).mappings().one()
+ assert row["callback_status"] == "pending"
+ assert row["callback_completed_at"] is None
def test_agent_run_callback_conflict_does_not_reserve_session(tmp_path: Path, capsys) -> None:
@@ -575,6 +892,201 @@ def test_agent_run_fork_session_reserves_new_session_and_persists_metadata(tmp_p
assert row["session_anchor"] == payload["session_id"]
+def test_agent_run_fork_self_uses_caller_session_and_inherits_scope(tmp_path: Path, capsys) -> None:
+ from sqlalchemy import select
+
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ source_session_id = _seed_bound_session(db_path, tmp_path)
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="reviewer", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--fork-self",
+ "--agent",
+ "reviewer",
+ "--async",
+ "--no-callback",
+ "--message",
+ "continue from here",
+ ]
+ )
+
+ with (
+ patch.dict("os.environ", {"AVIBE_SESSION_ID": source_session_id}),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["forked_from_session_id"] == source_session_id
+ assert payload["scope_id"] == "avibe::project::proj_fork_cli"
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == payload["session_id"])
+ ).mappings().one()
+ finally:
+ engine.dispose()
+ assert row["scope_id"] == "avibe::project::proj_fork_cli"
+ assert row["workdir"] == str(tmp_path)
+
+
+def test_agent_run_create_same_scope_uses_invocation_workdir(tmp_path: Path, capsys, monkeypatch) -> None:
+ from sqlalchemy import select
+
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+
+ state_home = tmp_path / "home"
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ caller_session_id = _seed_bound_session(db_path, tmp_path)
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(["--agent", "worker", "--same-scope", "--async", "--no-callback", "--message", "hi"])
+ monkeypatch.chdir(invoke_dir)
+
+ with (
+ patch.dict("os.environ", {"AVIBE_SESSION_ID": caller_session_id}),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["scope_id"] == "avibe::project::proj_fork_cli"
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == payload["session_id"])
+ ).mappings().one()
+ finally:
+ engine.dispose()
+ assert row["scope_id"] == "avibe::project::proj_fork_cli"
+ assert row["workdir"] == str(invoke_dir)
+
+
+def test_agent_run_create_scope_id_requires_existing_scope(tmp_path: Path, capsys) -> None:
+ from storage.importer import ensure_sqlite_state
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--scope-id",
+ "avibe::project::missing",
+ "--async",
+ "--no-callback",
+ "--message",
+ "hi",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 1
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "scope_not_found"
+
+
+def test_agent_run_create_scope_id_rejects_archived_project(tmp_path: Path, capsys) -> None:
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ with create_sqlite_engine(db_path).begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_archived",
+ now="2026-06-16T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=0,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--scope-id",
+ scope_id,
+ "--async",
+ "--no-callback",
+ "--message",
+ "hi",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 1
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "scope_archived"
+
+
def test_agent_run_fork_rejects_cross_backend_agent(tmp_path: Path, capsys) -> None:
from storage.importer import ensure_sqlite_state
@@ -705,15 +1217,51 @@ def test_agent_run_cwd_rejected_with_existing_session(capsys) -> None:
assert payload["code"] == "cwd_with_existing_session"
-def test_resolve_run_cwd_deliver_key_defers_to_scope(monkeypatch, tmp_path: Path) -> None:
- """Without --cwd, a --deliver-key reservation returns None so the target
- scope's configured workdir snapshot stays authoritative; an explicit --cwd
- still wins."""
+def test_resolve_run_cwd_deliver_key_defaults_to_invocation_cwd(monkeypatch, tmp_path: Path) -> None:
+ """Without --cwd, every blank session reservation snapshots the caller cwd.
+ An explicit --cwd still wins."""
from types import SimpleNamespace
monkeypatch.chdir(tmp_path)
args = SimpleNamespace(cwd=None, deliver_key="slack::channel::C123")
- assert cli._resolve_run_cwd(args, session_policy="create", help_command="x") is None
+ assert cli._resolve_run_cwd(args, session_policy="create", help_command="x") == str(tmp_path)
args = SimpleNamespace(cwd=str(tmp_path), deliver_key="slack::channel::C123")
assert cli._resolve_run_cwd(args, session_policy="create", help_command="x") == str(tmp_path)
+
+
+def test_runs_list_current_session_filters_from_caller_env(tmp_path: Path, capsys) -> None:
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ request_store.enqueue_agent_run(
+ message="current",
+ agent_name="worker",
+ session_id="ses-current",
+ )
+ request_store.enqueue_agent_run(
+ message="other",
+ agent_name="worker",
+ session_id="ses-other",
+ )
+ parser = cli.build_parser()
+ args = parser.parse_args(["runs", "list", "--current-session"])
+
+ with (
+ patch.dict("os.environ", {"AVIBE_SESSION_ID": "ses-current"}),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ ):
+ result = cli.cmd_runs_list(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert [run["session_id"] for run in payload["runs"]] == ["ses-current"]
+
+
+def test_runs_list_current_session_conflicts_with_session_id(capsys) -> None:
+ parser = cli.build_parser()
+ args = parser.parse_args(["runs", "list", "--current-session", "--session-id", "ses-explicit"])
+
+ result = cli.cmd_runs_list(args)
+
+ assert result == 1
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "conflicting_session_filter"
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 62d943037..42b267ce1 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -199,7 +199,9 @@ def test_task_add_help_includes_examples_and_threadless_guidance(capsys) -> None
assert "If this is your first time using this command, read this whole help entry before creating a task." in captured.out
assert "`--session-id` chooses which Agent Session Avibe will continue using when the task runs." in captured.out
assert "--post-to" in captured.out
- assert "--deliver-key" in captured.out
+ assert "--same-scope" in captured.out
+ assert "--scope-id" in captured.out
+ assert "--deliver-key" not in captured.out
assert "Cron weekday digits use APScheduler semantics: 0=Mon through 6=Sun; 7 is invalid." in captured.out
assert "Prefer weekday names such as mon, tue, or sun when scheduling by day of week." in captured.out
@@ -260,7 +262,7 @@ def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> Non
captured = capsys.readouterr()
assert "`vibe hook send` queues one deprecated asynchronous compatibility turn" in captured.out
assert "--post-to" in captured.out
- assert "--deliver-key" in captured.out
+ assert "--deliver-key" not in captured.out
assert "--session-id" in captured.out
assert "vibe agent run --async --session-id sesk8m4q2p7x --no-callback" in captured.out
@@ -274,10 +276,14 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:
assert exc.value.code == 0
captured = capsys.readouterr()
assert "--fork-session FORK_SESSION" in captured.out
- assert "Use --fork-session to create a new Session by forking an existing Session's native backend context." in captured.out
- assert "Forks keep the same backend as the source Session." in captured.out
- assert "vibe agent run --async --fork-session sesk8m4q2p7x --callback-session-id sescaller123" in captured.out
- assert "Do not combine --fork-session with --session-id, --create-session, --create-session-per-run, --deliver-key, or --post-to." in captured.out
+ assert "--fork-self" in captured.out
+ assert "--same-scope" in captured.out
+ assert "--scope-id" in captured.out
+ assert "--deliver-key" not in captured.out
+ assert "--fork-self forks the current caller Session from AVIBE_SESSION_ID." in captured.out
+ assert "Forks keep the same backend, scope, and cwd as the source Session." in captured.out
+ assert "vibe agent run --async --fork-self --message" in captured.out
+ assert "Do not combine fork flags with --session-id, --create-session, or --create-session-per-run." in captured.out
def test_task_add_parse_error_is_structured_json(capsys) -> None:
@@ -499,6 +505,217 @@ def test_task_add_records_caller_context_metadata(tmp_path: Path, capsys) -> Non
assert stored.metadata["created_by"] == expected
+def test_task_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="project-agent", backend="codex")
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ now = "2026-06-29T00:00:00+00:00"
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-scope-task", now=now)
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="project-agent",
+ agent_backend="codex",
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=json.dumps({"routing": {"agent_name": "project-agent"}}),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ store_path = tmp_path / "scheduled_tasks.json"
+ store = cli.ScheduledTaskStore(store_path)
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ args = _parse_task_add(
+ [
+ "--create-session-per-run",
+ "--scope-id",
+ "avibe::project::proj-scope-task",
+ "--cron",
+ "0 * * * *",
+ "--message",
+ "hello",
+ ]
+ )
+
+ with (
+ patch("os.getcwd", return_value=str(invoke_dir)),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["task"]["session_policy"] == "create_per_run"
+ assert payload["task"]["deliver_key"] is None
+ assert payload["task"]["cwd"] == str(invoke_dir)
+ assert payload["task"]["metadata"]["session_scope_id"] == "avibe::project::proj-scope-task"
+ assert payload["task"]["metadata"]["session_workdir"] == str(invoke_dir)
+ assert payload["task"]["agent_name"] == "project-agent"
+
+
+def test_task_add_create_session_scope_id_supports_project_scope(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="project-agent", backend="codex")
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ now = "2026-06-29T00:00:00+00:00"
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-once-task", now=now)
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="project-agent",
+ agent_backend="codex",
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=json.dumps({"routing": {"agent_name": "project-agent"}}),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ store_path = tmp_path / "scheduled_tasks.json"
+ store = cli.ScheduledTaskStore(store_path)
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ args = _parse_task_add(
+ [
+ "--create-session",
+ "--scope-id",
+ "avibe::project::proj-once-task",
+ "--at",
+ "2026-06-30T00:00:00+00:00",
+ "--message",
+ "hello",
+ ]
+ )
+
+ with (
+ patch("os.getcwd", return_value=str(invoke_dir)),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["task"]["session_policy"] == "create_once"
+ target = cli.resolve_session_id_target(payload["task"]["session_id"], db_path=db_path)
+ assert target.session_key.session_scope == "avibe::project::proj-once-task"
+ assert target.workdir == str(invoke_dir)
+ assert payload["task"]["cwd"] == str(invoke_dir)
+ assert payload["task"]["metadata"]["session_scope_id"] == "avibe::project::proj-once-task"
+ assert payload["task"]["metadata"]["session_workdir"] == str(invoke_dir)
+
+
+def test_task_add_create_session_scope_id_uses_unique_definition_anchors(tmp_path: Path, capsys) -> None:
+ from sqlalchemy import select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-once-unique", now="2026-06-16T00:00:00Z")
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+
+ payloads = []
+ for cron in ("0 * * * *", "30 * * * *"):
+ args = _parse_task_add(
+ [
+ "--agent",
+ "worker",
+ "--create-session",
+ "--scope-id",
+ scope_id,
+ "--cron",
+ cron,
+ "--message",
+ "hello",
+ ]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("os.getcwd", return_value=str(invoke_dir)),
+ ):
+ assert cli.cmd_task_add(args) == 0
+ payloads.append(json.loads(capsys.readouterr().out))
+
+ with engine.connect() as conn:
+ rows = list(
+ conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.session_anchor)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .order_by(agent_sessions.c.created_at, agent_sessions.c.id)
+ ).mappings()
+ )
+
+ assert {payload["task"]["session_id"] for payload in payloads} == {row["id"] for row in rows}
+ anchors = {row["session_anchor"] for row in rows}
+ assert len(anchors) == 2
+ assert all(anchor.startswith("avibe_proj-once-unique:definition_") for anchor in anchors)
+
+
def test_task_add_defaults_target_to_caller_session(tmp_path: Path, capsys) -> None:
db_path = tmp_path / "state" / "vibe.sqlite"
agent_store = cli.VibeAgentStore(db_path)
@@ -551,6 +768,29 @@ def test_task_add_defaults_target_to_caller_session(tmp_path: Path, capsys) -> N
}
+def test_task_add_rejects_scope_without_session_creation() -> None:
+ parser = cli.build_parser()
+ args = parser.parse_args(
+ [
+ "task",
+ "add",
+ "--session-id",
+ "sesExisting",
+ "--scope-id",
+ "avibe::project::proj-ignored",
+ "--cron",
+ "0 * * * *",
+ "--message",
+ "hello",
+ ]
+ )
+
+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)
+
+ assert result == 1
+ assert payload["code"] == "scope_without_session_creation"
+
+
def test_task_update_missing_id_returns_guidance(tmp_path: Path) -> None:
store_path = tmp_path / "scheduled_tasks.json"
@@ -787,6 +1027,147 @@ def test_task_update_modifies_existing_task_without_changing_id(tmp_path: Path,
assert payload["task"]["prompt"] == "updated"
+def test_task_update_rejects_scope_without_session_creation(tmp_path: Path) -> None:
+ store_path = tmp_path / "scheduled_tasks.json"
+ store = cli.ScheduledTaskStore(store_path)
+ task = store.add_task(
+ session_id="sesExisting",
+ session_key="",
+ prompt="hello",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="Asia/Shanghai",
+ )
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--scope-id", "avibe::project::proj-ignored"])
+
+ with patch("vibe.cli._task_store", return_value=store):
+ result, payload = _capture_stderr_json(cli.cmd_task_update, args)
+
+ assert result == 1
+ assert payload["code"] == "scope_without_session_creation"
+
+
+def test_task_update_rejects_cwd_for_already_reserved_create_once_task(tmp_path: Path) -> None:
+ store_path = tmp_path / "scheduled_tasks.json"
+ store = cli.ScheduledTaskStore(store_path)
+ task = store.add_task(
+ session_id="sesExisting",
+ session_key="",
+ prompt="hello",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="Asia/Shanghai",
+ agent_name="worker",
+ session_policy="create_once",
+ cwd=str(tmp_path / "old"),
+ metadata={"session_scope_id": "avibe::project::proj-existing"},
+ )
+ new_cwd = tmp_path / "new"
+ new_cwd.mkdir()
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--cwd", str(new_cwd)])
+
+ with patch("vibe.cli._task_store", return_value=store):
+ result, payload = _capture_stderr_json(cli.cmd_task_update, args)
+
+ assert result == 1
+ assert payload["code"] == "cwd_with_existing_session"
+
+
+def test_task_update_create_session_preserves_existing_cwd_without_cwd_flag(tmp_path: Path, capsys) -> None:
+ from sqlalchemy import select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ saved_cwd = tmp_path / "saved"
+ saved_cwd.mkdir()
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-replace-cwd", now="2026-06-16T00:00:00Z")
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="sesOld",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ agent_variant="codex",
+ session_anchor="avibe_proj-replace-cwd:definition_old",
+ native_session_id="native-old",
+ status="active",
+ metadata_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ last_active_at="2026-06-16T00:00:00Z",
+ workdir=str(saved_cwd),
+ )
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_id="sesOld",
+ session_key="",
+ prompt="hello",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="Asia/Shanghai",
+ agent_name="worker",
+ session_policy="create_once",
+ cwd=str(saved_cwd),
+ metadata={"session_scope_id": scope_id, "session_workdir": str(saved_cwd)},
+ )
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--create-session"])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("os.getcwd", return_value=str(invoke_dir)),
+ ):
+ result = cli.cmd_task_update(args)
+
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions.c.workdir).where(agent_sessions.c.id == store.get_task(task.id).session_id).limit(1)
+ ).mappings().one()
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["task"]["cwd"] == str(saved_cwd)
+ assert payload["task"]["metadata"]["session_workdir"] == str(saved_cwd)
+ assert row["workdir"] == str(saved_cwd)
+ assert payload["task"]["session_id"] != "sesOld"
+
+
def test_task_update_session_key_clears_previous_session_id(tmp_path: Path, capsys) -> None:
store_path = tmp_path / "scheduled_tasks.json"
store = cli.ScheduledTaskStore(store_path)
@@ -840,6 +1221,42 @@ def test_task_update_replaces_post_to_with_deliver_key(tmp_path: Path, capsys) -
assert payload["task"]["deliver_key"] == "slack::channel::C999"
+def test_task_update_reset_delivery_preserves_creation_scope_metadata(tmp_path: Path, capsys) -> None:
+ store_path = tmp_path / "scheduled_tasks.json"
+ store = cli.ScheduledTaskStore(store_path)
+ task = store.add_task(
+ session_key="",
+ prompt="hello",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="Asia/Shanghai",
+ agent_name="worker",
+ session_policy="create_per_run",
+ post_to="channel",
+ metadata={
+ "session_scope_id": "avibe::project::proj-reset-task",
+ "session_workdir": str(tmp_path),
+ },
+ )
+ agent_store = cli.VibeAgentStore(tmp_path / "state" / "vibe.sqlite")
+ agent_store.create(name="worker", backend="codex")
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--reset-delivery"])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["task"]["post_to"] is None
+ assert payload["task"]["deliver_key"] is None
+ assert payload["task"]["metadata"]["session_scope_id"] == "avibe::project::proj-reset-task"
+
+
def test_task_add_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Path, capsys) -> None:
parser = cli.build_parser()
args = parser.parse_args(
@@ -1078,7 +1495,126 @@ def test_agent_run_create_session_uses_scope_anchor_for_channel_deliver_key(tmp_
target = cli.resolve_session_id_target(payload["session_id"], db_path=db_path)
assert target.session_key.to_key() == "slack::channel::C123"
assert target.session_key.thread_id is None
- assert target.session_anchor == "slack_C123"
+ assert target.session_anchor.startswith("slack_C123:run_")
+
+
+def test_agent_run_create_session_preserves_legacy_thread_deliver_key(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--async",
+ "--no-callback",
+ "--create-session",
+ "--deliver-key",
+ "slack::channel::C123::thread::171717.123",
+ "--message",
+ "hello",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["deliver_key"] == "slack::channel::C123::thread::171717.123"
+ target = cli.resolve_session_id_target(payload["session_id"], db_path=db_path)
+ assert target.session_key.to_key() == "slack::channel::C123::thread::171717.123"
+ assert target.session_key.thread_id == "171717.123"
+ assert target.session_anchor.startswith("slack_171717.123:run_")
+ queued = request_store.get_run(payload["run_id"])
+ assert queued is not None
+ assert queued["deliver_key"] == "slack::channel::C123::thread::171717.123"
+
+
+def test_agent_run_create_session_scope_id_uses_unique_project_anchors(tmp_path: Path, capsys) -> None:
+ from sqlalchemy import select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_unique",
+ now="2026-06-16T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+
+ payloads = []
+ for message in ("one", "two"):
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--async",
+ "--no-callback",
+ "--create-session",
+ "--scope-id",
+ scope_id,
+ "--message",
+ message,
+ ]
+ )
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ assert cli.cmd_agent_run(args) == 0
+ payloads.append(json.loads(capsys.readouterr().out))
+
+ with engine.connect() as conn:
+ rows = list(
+ conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.session_anchor)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .order_by(agent_sessions.c.created_at, agent_sessions.c.id)
+ ).mappings()
+ )
+
+ assert {payload["session_id"] for payload in payloads} == {row["id"] for row in rows}
+ anchors = {row["session_anchor"] for row in rows}
+ assert len(anchors) == 2
+ assert all(anchor.startswith("avibe_proj_unique:run_") for anchor in anchors)
def test_agent_run_private_async_uses_no_delivery_channel_scope_for_lark(tmp_path: Path, capsys) -> None:
@@ -1139,7 +1675,7 @@ def test_agent_run_rejects_per_run_for_direct_invocation() -> None:
assert payload["code"] == "invalid_session_policy"
-def test_agent_run_rejects_backend_mismatch_for_existing_session(tmp_path: Path) -> None:
+def test_agent_run_rejects_cross_backend_agent_for_existing_session(tmp_path: Path) -> None:
db_path = tmp_path / "state" / "vibe.sqlite"
agent_store = cli.VibeAgentStore(db_path)
agent_store.create(name="codex-worker", backend="codex")
@@ -1166,6 +1702,79 @@ def test_agent_run_rejects_backend_mismatch_for_existing_session(tmp_path: Path)
assert payload["code"] == "agent_session_backend_mismatch"
+def test_agent_run_existing_session_allows_matching_agent_hint(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="codex-worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = service.reserve_private_agent_session(
+ platform="slack",
+ agent_backend="codex",
+ agent_name="codex-worker",
+ session_anchor="slack_private-agent-test",
+ )
+ finally:
+ service.close()
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "codex-worker",
+ "--async",
+ "--no-callback",
+ "--session-id",
+ session_id,
+ "--message",
+ "hello",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["session_id"] == session_id
+ assert payload["agent"] == "codex-worker"
+
+
+def test_agent_run_rejects_different_same_backend_agent_for_existing_session(tmp_path: Path) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="session-worker", backend="codex")
+ agent_store.create(name="other-worker", backend="codex")
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = service.reserve_private_agent_session(
+ platform="slack",
+ agent_backend="codex",
+ agent_name="session-worker",
+ session_anchor="slack_private-agent-test",
+ )
+ finally:
+ service.close()
+ args = _parse_agent_run(["--agent", "other-worker", "--session-id", session_id, "--message", "hello"])
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result, payload = _capture_stderr_json(cli.cmd_agent_run, args)
+
+ assert result == 1
+ assert payload["code"] == "agent_session_agent_mismatch"
+
+
def test_agent_run_rejects_post_to_thread_for_threadless_session_before_enqueue(tmp_path: Path) -> None:
db_path = tmp_path / "state" / "vibe.sqlite"
agent_store = cli.VibeAgentStore(db_path)
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 7719bca98..85645d2b5 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -296,6 +296,136 @@ def test_watch_add_records_caller_context_metadata(tmp_path: Path, capsys) -> No
assert stored.metadata["created_by"] == expected
+def test_watch_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="project-agent", backend="codex")
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ now = "2026-06-29T00:00:00+00:00"
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-scope-watch", now=now)
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="project-agent",
+ agent_backend="codex",
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=json.dumps({"routing": {"agent_name": "project-agent"}}),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ args = _parse_watch_add(
+ [
+ "--create-session-per-run",
+ "--scope-id",
+ "avibe::project::proj-scope-watch",
+ "--shell",
+ "python3 scripts/wait.py",
+ ]
+ )
+
+ with (
+ patch("os.getcwd", return_value=str(invoke_dir)),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=lambda *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
+ ):
+ result = cli.cmd_watch_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["watch"]["session_policy"] == "create_per_run"
+ assert payload["watch"]["deliver_key"] is None
+ assert payload["watch"]["cwd"] == str(invoke_dir)
+ assert payload["watch"]["metadata"]["session_scope_id"] == "avibe::project::proj-scope-watch"
+ assert payload["watch"]["metadata"]["session_workdir"] == str(invoke_dir)
+ assert payload["watch"]["agent_name"] == "project-agent"
+
+
+def test_watch_add_create_session_scope_id_uses_invocation_cwd(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="project-agent", backend="codex")
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ now = "2026-06-29T00:00:00+00:00"
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-watch-once", now=now)
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="project-agent",
+ agent_backend="codex",
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=json.dumps({"routing": {"agent_name": "project-agent"}}),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ invoke_dir = tmp_path / "invoke"
+ invoke_dir.mkdir()
+ args = _parse_watch_add(
+ [
+ "--create-session",
+ "--scope-id",
+ "avibe::project::proj-watch-once",
+ "--shell",
+ "python3 scripts/wait.py",
+ ]
+ )
+
+ with (
+ patch("os.getcwd", return_value=str(invoke_dir)),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=lambda *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
+ ):
+ result = cli.cmd_watch_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ target = cli.resolve_session_id_target(payload["watch"]["session_id"], db_path=db_path)
+ assert target.workdir == str(invoke_dir)
+ assert payload["watch"]["cwd"] == str(invoke_dir)
+ assert payload["watch"]["metadata"]["session_workdir"] == str(invoke_dir)
+
+
def test_watch_add_defaults_target_to_caller_session(tmp_path: Path, capsys) -> None:
db_path = tmp_path / "state" / "vibe.sqlite"
agent_store = cli.VibeAgentStore(db_path)
@@ -786,6 +916,50 @@ def test_watch_update_session_key_clears_previous_session_id(tmp_path: Path, cap
assert payload["watch"]["session_key"] == "slack::channel::C456"
+def test_watch_update_reset_delivery_preserves_creation_scope_metadata(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=str(tmp_path),
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key="avibe::project::proj-reset-watch",
+ agent_name="worker",
+ session_policy="create_per_run",
+ metadata={
+ "session_scope_id": "avibe::project::proj-reset-watch",
+ "session_workdir": str(tmp_path),
+ },
+ )
+ agent_store = cli.VibeAgentStore(tmp_path / "state" / "vibe.sqlite")
+ agent_store.create(name="worker", backend="codex")
+ args = _parse_watch_update([watch.id, "--reset-delivery"])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_update(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["watch"]["post_to"] is None
+ assert payload["watch"]["deliver_key"] is None
+ assert payload["watch"]["metadata"]["session_scope_id"] == "avibe::project::proj-reset-watch"
+ assert payload["watch"]["metadata"]["session_workdir"] == str(tmp_path)
+
+
def test_watch_update_replaces_argv_command(tmp_path: Path, capsys) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -848,6 +1022,122 @@ def test_watch_update_no_changes_returns_structured_error(tmp_path: Path) -> Non
assert payload["code"] == "no_watch_changes"
+def test_watch_update_rejects_scope_without_session_creation(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_id="sesExisting",
+ session_key="",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+ args = _parse_watch_update([watch.id, "--scope-id", "avibe::project::proj-ignored"])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._watch_store", return_value=store),
+ ):
+ result, payload = _capture_stderr_json(cli.cmd_watch_update, args)
+
+ assert result == 1
+ assert payload["code"] == "scope_without_session_creation"
+
+
+def test_watch_update_allows_cwd_for_already_reserved_create_once_watch(tmp_path: Path, capsys) -> None:
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, scope_settings
+ from storage.settings_service import upsert_scope
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ now = "2026-06-16T00:00:00Z"
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-existing", now=now)
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="sesExisting",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ agent_variant="codex",
+ session_anchor="avibe_proj-existing:definition_old",
+ native_session_id="native-old",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ workdir=str(tmp_path / "old"),
+ )
+ )
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_id="sesExisting",
+ session_key="",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=str(tmp_path / "old"),
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ agent_name="worker",
+ session_policy="create_once",
+ metadata={"session_scope_id": "avibe::project::proj-existing"},
+ )
+ new_cwd = tmp_path / "new"
+ new_cwd.mkdir()
+ args = _parse_watch_update([watch.id, "--cwd", str(new_cwd)])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_watch_update(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["watch"]["session_id"] == "sesExisting"
+ assert payload["watch"]["cwd"] == str(new_cwd)
+ assert payload["watch"]["metadata"]["session_workdir"] == str(new_cwd)
+
+
def test_watch_update_rejects_deprecated_prompt_argument(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
watch = store.add_watch(
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index b4b5e350c..0ad76365a 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -330,22 +330,17 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("select name from sqlite_master where type='table' order by name", prompt)
self.assertIn("schema discovery, current session lookup, existing task/watch inspection, Agent run history", prompt)
self.assertIn("### Choosing the right Harness shape", prompt)
- self.assertIn("| Independent Agent delegation | `vibe agent run --create-session` |", prompt)
+ self.assertIn("| Independent Agent delegation | `vibe agent run --agent <agent-name>` |", prompt)
self.assertIn("| Same-session follow-up | `vibe agent run --session-id ...` |", prompt)
- self.assertIn("| Branch from existing Session context | `vibe agent run --fork-session ...` |", prompt)
+ self.assertIn("| Branch from current Session context | `vibe agent run --fork-self ...` |", prompt)
self.assertIn("`vibe task add` creates a time-triggered saved Agent message", prompt)
self.assertIn("`vibe watch add` creates a managed monitor", prompt)
self.assertIn("product signals, business events, files, logs, CI/reviews/deploys", prompt)
- self.assertIn("Use `vibe agent run --async ...` when one Agent delegates work", prompt)
- self.assertIn("Avibe injects this Session as the default async callback target", prompt)
- self.assertIn("Pass `--no-callback` only when you intentionally want no automatic follow-up", prompt)
- self.assertIn("final result text should return to this caller Session", prompt)
- self.assertIn("vibe agent run --fork-session <source-session-id> --message ...", prompt)
- self.assertIn("Forks keep the source Session backend", prompt)
- self.assertIn(
- "`--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel.",
- prompt,
- )
+ self.assertIn("Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work", prompt)
+ self.assertIn("Add `--same-scope` when the new Session should live under the same Workbench project or IM scope", prompt)
+ self.assertIn("Use `vibe agent run --fork-self --message ...` when work should branch from this current Session", prompt)
+ self.assertIn("Forks keep the source Session backend, scope, and cwd by default", prompt)
+ self.assertIn("`--post-to` is a delivery override, not session placement", prompt)
self.assertIn("Manage existing work with `vibe task <list|show|pause|resume|run|remove>`", prompt)
self.assertIn("`vibe watch <list|show|pause|resume|remove>`", prompt)
self.assertIn("`vibe runs <list|show|cancel>`", prompt)
@@ -361,12 +356,13 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("CLI Token", prompt)
self.assertIn("Use the `Agent Name` value exactly as listed in shell commands", prompt)
self.assertIn("`--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing", prompt)
- self.assertIn("`--create-session` creates a separate Session for the target Agent", prompt)
- self.assertIn("`--fork-session <id>` creates a new Agent Session from that source Session's native backend context", prompt)
- self.assertIn("vibe agent run --agent <agent-name> --create-session --message ...", prompt)
+ self.assertIn("Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate private/background Session", prompt)
+ self.assertIn("`--fork-self` creates a new Agent Session from this current Session's native backend context", prompt)
+ self.assertIn("`--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context", prompt)
+ self.assertIn("vibe agent run --agent <agent-name> --message ...", prompt)
self.assertIn("vibe agent run --agent <agent-name> --session-id ... --message ...", prompt)
self.assertIn("Reuse the current session id only with Agents whose `Backend` matches `codex`; otherwise use `--create-session`", prompt)
- self.assertIn("With `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides", prompt)
+ self.assertIn("With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides", prompt)
self.assertIn("`--async` changes waiting behavior, not session identity", prompt)
self.assertIn("inspected later with `vibe runs`", prompt)
self.assertNotIn("--create-session-per-run", prompt)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 08b39806c..f2cac28ee 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -1219,6 +1219,76 @@ def test_runtime_session_reservation_uses_default_agent_without_scope_agent(
assert target.agent_name == "codex"
+def test_runtime_session_reservation_uses_unique_anchors_for_reused_scope(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ monkeypatch.setattr(paths, "get_state_dir", lambda: db_path.parent)
+ monkeypatch.setattr(paths, "get_sqlite_state_path", lambda: db_path)
+
+ from core.vibe_agents import VibeAgentStore
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, scope_settings
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.ensure_builtin_default_agents(["codex"])
+ agent_store.set_default_agent_name("codex")
+ finally:
+ agent_store.close()
+
+ with create_sqlite_engine(db_path).begin() as conn:
+ now = "2026-05-22T00:00:00+00:00"
+ scope_id = upsert_scope(conn, "slack", "channel", "C789", now=now)
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=None,
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=json.dumps({}),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ controller = SimpleNamespace(agent_router=SimpleNamespace(global_default="codex"))
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ )
+
+ first_session_id = service._reserve_runtime_session(agent_name=None, deliver_key="slack::channel::C789")
+ second_session_id = service._reserve_runtime_session(agent_name=None, deliver_key="slack::channel::C789")
+
+ with create_sqlite_engine(db_path).connect() as conn:
+ rows = list(
+ conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.session_anchor)
+ .where(agent_sessions.c.id.in_([first_session_id, second_session_id]))
+ .order_by(agent_sessions.c.id)
+ ).mappings()
+ )
+
+ anchors = {row["session_anchor"] for row in rows}
+ assert len(rows) == 2
+ assert len(anchors) == 2
+ assert all(anchor.startswith("slack_C789:runtime_") for anchor in anchors)
+ assert resolve_session_id_target(first_session_id, db_path=db_path).session_key.to_key() == "slack::channel::C789"
+ assert resolve_session_id_target(second_session_id, db_path=db_path).session_key.to_key() == "slack::channel::C789"
+
+
def test_request_store_constructor_does_not_requeue_processing_files(tmp_path: Path) -> None:
root = tmp_path / "task_requests"
store = TaskExecutionStore(root)
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index ba65fa728..3da769a86 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -681,6 +681,175 @@ def test_reserve_forked_session_keeps_im_anchor_and_resets_variant_for_agent_ove
assert resolved.session_key.to_key() == "slack::channel::C123::thread::171717.123"
+def test_reserve_forked_session_reanchors_when_moved_to_new_im_scope(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ SQLiteSessionsService(db_path).close()
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ source_scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C123",
+ now="2026-06-16T00:00:00Z",
+ )
+ target_scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C999",
+ now="2026-06-16T00:00:00Z",
+ )
+ for scope_id in (source_scope_id, target_scope_id):
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ source_id = create_agent_session_row(
+ conn,
+ scope_id=source_scope_id,
+ session_anchor="slack_171717.123",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-worker",
+ agent_name="worker",
+ workdir=str(tmp_path),
+ native_session_id="thread-source",
+ metadata={
+ "legacy_scope_key": source_scope_id,
+ "private_agent_run": True,
+ "no_delivery": True,
+ },
+ )
+ finally:
+ engine.dispose()
+
+ first_result = reserve_forked_session(
+ source_session_id=source_id,
+ scope_id=target_scope_id,
+ db_path=db_path,
+ )
+ second_result = reserve_forked_session(
+ source_session_id=source_id,
+ scope_id=target_scope_id,
+ db_path=db_path,
+ )
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ rows = list(
+ conn.execute(
+ select(agent_sessions)
+ .where(agent_sessions.c.id.in_([first_result.session_id, second_result.session_id]))
+ .order_by(agent_sessions.c.id)
+ ).mappings()
+ )
+ finally:
+ engine.dispose()
+
+ assert len(rows) == 2
+ row = rows[0]
+ metadata = json.loads(row["metadata_json"])
+ assert row["scope_id"] == target_scope_id
+ assert row["session_anchor"].startswith("slack_C999:fork_")
+ assert metadata["fork_target_scope_id"] == target_scope_id
+ assert metadata["legacy_scope_key"] == target_scope_id
+ assert "private_agent_run" not in metadata
+ assert "no_delivery" not in metadata
+ assert rows[0]["session_anchor"] != rows[1]["session_anchor"]
+
+ resolved = resolve_session_id_target(first_result.session_id, db_path=db_path)
+ assert resolved.session_key.to_key() == "slack::channel::C999"
+ assert resolved.session_key.thread_id is None
+ assert resolved.session_anchor.startswith("slack_C999:fork_")
+ assert resolved.suppress_delivery is False
+
+
+def test_reserve_forked_session_reanchors_explicit_parent_scope(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ SQLiteSessionsService(db_path).close()
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C123",
+ now="2026-06-16T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ source_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_171717.123",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-worker",
+ agent_name="worker",
+ workdir=str(tmp_path),
+ native_session_id="thread-source",
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(
+ source_session_id=source_id,
+ scope_id=scope_id,
+ db_path=db_path,
+ )
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == result.session_id).limit(1)
+ ).mappings().one()
+ finally:
+ engine.dispose()
+
+ assert row["scope_id"] == scope_id
+ assert row["session_anchor"].startswith("slack_C123:fork_")
+
+ resolved = resolve_session_id_target(result.session_id, db_path=db_path)
+ assert resolved.session_key.to_key() == "slack::channel::C123"
+ assert resolved.session_key.thread_id is None
+ assert resolved.session_anchor.startswith("slack_C123:fork_")
+
+
def test_reserve_forked_session_rejects_backend_change(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
source_id = _seed_source_session(db_path, tmp_path)
diff --git a/vibe/cli.py b/vibe/cli.py
index d7259fe3d..86baaa875 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -35,6 +35,7 @@ from config.v2_config import V2Config
from core.scheduled_tasks import (
ScheduledTaskStore,
TaskExecutionStore,
+ parse_scope_id,
parse_session_key,
resolve_session_id_target,
session_anchor_for_target,
@@ -61,7 +62,7 @@ from vibe.upgrade import (
)
from storage.db import create_sqlite_engine
from storage.background import compute_next_run_at, normalize_run_status
-from storage.models import scope_settings
+from storage.models import scope_settings, scopes
from storage.pagination import DEFAULT_PAGE_LIMIT, PageRequest, make_page_request, pagination_payload
from storage.read_only_query import ReadOnlyQueryError, run_read_only_query
from storage.settings_service import make_scope_id
@@ -279,7 +280,8 @@ def _task_add_examples_text() -> str:
`--session-id` chooses which Agent Session Avibe will continue using when the task runs.
Omit --session-id only when this task should follow the current caller Session.
`--post-to channel` changes where the message is posted, not which session is continued.
- Use --deliver-key only when delivery must go to a different explicit target.
+ Use --create-session with --same-scope to create a reusable sibling Session in the current Workbench project or IM scope.
+ Use --create-session with --scope-id <scopes.id> to create a reusable Session in a specific existing scope.
`--message` and `--message-file` provide the stored user message that will be sent each time the task runs.
Use --cron for recurring jobs and --at for one-shot jobs.
Cron weekday digits use APScheduler semantics: 0=Mon through 6=Sun; 7 is invalid. Prefer weekday names such as mon, tue, or sun when scheduling by day of week.
@@ -288,7 +290,7 @@ def _task_add_examples_text() -> str:
Examples:
vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --message 'Tell a new joke each time.'
- vibe task add --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --cron '0 9 * * *' --message 'Post the daily summary in the announcements channel.'
+ vibe task add --create-session --same-scope --cron '0 9 * * *' --message 'Post a visible daily summary in this scope.'
"""
)
@@ -303,12 +305,13 @@ def _task_update_examples_text() -> str:
vibe task update 12ab34cd56ef --cron '*/30 * * * *'
vibe task update 12ab34cd56ef --message 'Send a shorter summary.'
vibe task update 12ab34cd56ef --session-id sesk8m4q2p7x --post-to channel
- vibe task update 12ab34cd56ef --deliver-key 'slack::channel::C999'
+ vibe task update 12ab34cd56ef --create-session --same-scope
vibe task update 12ab34cd56ef --reset-delivery
Guidance:
Unspecified fields keep their existing values.
Use --reset-delivery to return to following the session target directly.
+ Use --same-scope or --scope-id when this task should create new Sessions in a specific scope.
When changing schedule fields, pass either --cron or --at.
Cron weekday digits use APScheduler semantics: 0=Mon through 6=Sun; 7 is invalid. Prefer weekday names such as mon, tue, or sun when scheduling by day of week.
Use --clear-name if you want the task to stop storing a custom name.
@@ -333,7 +336,7 @@ def _hook_send_examples_text() -> str:
Keep the current session id when the hook should continue in the same session.
If no session id is available, trigger this from an active Avibe conversation instead of guessing.
`--post-to channel` changes where the message is posted, not which session is continued.
- Use --deliver-key only when delivery must go to a different explicit target.
+ For new async one-shot work, prefer `vibe agent run --async`.
`--message` and `--message-file` provide the one-shot async user message that will be queued immediately.
Examples:
@@ -616,7 +619,8 @@ def _watch_add_examples_text() -> str:
`--session-id` chooses which Agent Session Avibe will continue using for follow-up messages from the watch.
Omit --session-id only when this watch should follow up in the current caller Session.
`--post-to channel` changes where the follow-up is posted, not which session is continued.
- Use --deliver-key only when delivery must go to a different explicit target.
+ Use --create-session with --same-scope to create a reusable sibling Session in the current Workbench project or IM scope.
+ Use --create-session with --scope-id <scopes.id> to create a reusable Session in a specific existing scope.
`--prefix` becomes the instruction text of the follow-up hook. On a successful cycle, Avibe prepends `--prefix` before waiter stdout and joins them with a blank line when both exist.
Terminal failures also send a follow-up and disable the watch.
In forever mode, failures are retried only when the waiter exits with an allowed `--retry-exit-code`.
@@ -636,19 +640,22 @@ def _agent_run_examples_text() -> str:
"""\
Session target:
Use --session-id to continue an existing Agent Session.
- Use --create-session to start a new blank Session.
- Use --fork-session to create a new Session by forking an existing Session's native backend context.
+ Omit --session-id/--fork-self/--fork-session to create a private background Session for --agent.
+ Use --same-scope to place a new Session in the caller/source Session's scope.
+ Use --scope-id <scopes.id> to place a new Session in a specific existing scope.
Forking:
+ --fork-self forks the current caller Session from AVIBE_SESSION_ID.
--fork-session <session-id> creates a new Avibe Agent Session and asks the native backend to fork the source native session on the first turn.
- Forks keep the same backend as the source Session. Passing --agent is allowed only when that Agent uses the same backend.
+ Forks keep the same backend, scope, and cwd as the source Session. Passing --agent is allowed only when that Agent uses the same backend.
--agent, --model, and --reasoning-effort may override the forked Session's Agent/model/effort.
- Do not combine --fork-session with --session-id, --create-session, --create-session-per-run, --deliver-key, or --post-to.
+ Do not combine fork flags with --session-id, --create-session, or --create-session-per-run.
Examples:
vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'
+ vibe agent run --agent release-reviewer --same-scope --message 'Review this project in a visible sibling Session.'
vibe agent run --async --session-id sesk8m4q2p7x --no-callback --message 'The export finished. Share the summary.'
- vibe agent run --async --fork-session sesk8m4q2p7x --callback-session-id sescaller123 --message 'Explore this alternate fix from the current context.'
+ vibe agent run --async --fork-self --message 'Explore this alternate fix from the current context.'
vibe agent run --fork-session sesk8m4q2p7x --agent reviewer --model gpt-5.4 --reasoning-effort high --message 'Review the forked context.'
"""
)
@@ -971,21 +978,25 @@ def _normalize_watch_name(value: Optional[str], *, help_command: str = "vibe wat
return normalized
-def _resolve_watch_cwd(value: Optional[str], *, help_command: str) -> Optional[str]:
- if not value:
- return None
+def _resolve_existing_cwd(value: str, *, help_command: str, code: str, label: str) -> str:
resolved = Path(value).expanduser().resolve()
if not resolved.exists() or not resolved.is_dir():
raise TaskCliError(
- f"watch cwd does not exist: {value}",
- code="invalid_watch_cwd",
- hint="Point --cwd to an existing directory, or omit it to inherit the service working directory.",
+ f"{label} cwd does not exist: {value}",
+ code=code,
+ hint="Point --cwd to an existing directory, or omit it to use the invocation directory.",
help_command=help_command,
details={"cwd": value},
)
return str(resolved)
+def _resolve_watch_cwd(value: Optional[str], *, help_command: str, default_to_invocation: bool = False) -> Optional[str]:
+ if not value:
+ return os.getcwd() if default_to_invocation else None
+ return _resolve_existing_cwd(value, help_command=help_command, code="invalid_watch_cwd", label="watch")
+
+
def _validate_watch_timing(
*,
timeout_seconds: float,
@@ -1348,6 +1359,18 @@ def _resolve_caller_session_id(args, *, purpose: str, help_command: str) -> tupl
return session_id, notice
+def _require_caller_session_id(caller_context, *, purpose: str, help_command: str) -> str:
+ session_id = _default_session_id_from_caller(caller_context)
+ if session_id:
+ return session_id
+ raise TaskCliError(
+ f"{purpose} requires an Avibe Agent caller Session.",
+ code="missing_caller_session",
+ hint="Run this command from an Avibe Agent shell where AVIBE_SESSION_ID is injected, or pass an explicit Session ID.",
+ help_command=help_command,
+ )
+
+
def _default_run_id_from_caller(caller_context) -> Optional[str]:
if caller_context is None:
return None
@@ -1377,6 +1400,192 @@ def _resolve_caller_run_id(args, *, purpose: str, help_command: str) -> tuple[st
}
+def _parse_validated_scope_id(scope_id: str, *, help_command: str):
+ try:
+ target = parse_scope_id(scope_id)
+ except ValueError as exc:
+ raise TaskCliError(
+ str(exc),
+ code="invalid_scope_id",
+ hint="Pass a Scope ID from the scopes table, for example avibe::project::proj_123.",
+ example="avibe::project::proj_abc123",
+ help_command=help_command,
+ details={"scope_id": scope_id},
+ ) from exc
+
+ supported_platforms = _supported_task_platforms()
+ if target.platform not in supported_platforms:
+ supported_text = ", ".join(sorted(supported_platforms)) or "none"
+ raise TaskCliError(
+ f"unsupported scope platform: {target.platform}",
+ code="unsupported_platform",
+ hint="Choose a scope whose platform is enabled in Avibe before sending the request.",
+ example="avibe::project::proj_abc123",
+ help_command=help_command,
+ details={
+ "requested_platform": target.platform,
+ "configured_platforms": sorted(supported_platforms),
+ "configured_platforms_text": supported_text,
+ },
+ )
+ return target
+
+
+def _validate_existing_scope_id(scope_id: str, *, help_command: str):
+ target = _parse_validated_scope_id(scope_id, help_command=help_command)
+ _ensure_cli_sqlite_state()
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.connect() as conn:
+ found = conn.execute(
+ select(scopes.c.id, scope_settings.c.enabled)
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(scopes.c.id == target.session_scope)
+ .limit(1)
+ ).mappings().first()
+ finally:
+ engine.dispose()
+ if found is None:
+ raise TaskCliError(
+ f"scope id not found: {target.session_scope}",
+ code="scope_not_found",
+ hint="Pass an existing Scope ID, or use --same-scope from an Avibe Agent Session.",
+ help_command=help_command,
+ details={"scope_id": target.session_scope},
+ )
+ if target.platform == "avibe" and target.scope_type == "project" and found["enabled"] is not None and not bool(found["enabled"]):
+ raise TaskCliError(
+ f"scope id is archived: {target.session_scope}",
+ code="scope_archived",
+ hint="Choose an active Workbench project scope.",
+ help_command=help_command,
+ details={"scope_id": target.session_scope},
+ )
+ return target
+
+
+def _scope_id_from_session_id(session_id: str, *, help_command: str) -> str:
+ resolved = resolve_session_id_target(session_id)
+ return resolved.session_key.to_key(include_thread=False)
+
+
+def _legacy_scope_key_from_target(value: Optional[str]) -> str:
+ if not value:
+ return ""
+ try:
+ return parse_scope_id(value).session_scope
+ except ValueError:
+ try:
+ return parse_session_key(value).session_scope
+ except ValueError:
+ return ""
+
+
+def _resolve_agent_run_scope_key(args, *, caller_context, source_session_id: Optional[str]) -> Optional[str]:
+ raw_scope_id = (getattr(args, "scope_id", None) or "").strip()
+ if raw_scope_id:
+ return _validate_existing_scope_id(raw_scope_id, help_command="vibe agent run --help").session_scope
+ if bool(getattr(args, "same_scope", False)):
+ if source_session_id:
+ return _scope_id_from_session_id(source_session_id, help_command="vibe agent run --help")
+ caller_session_id = _require_caller_session_id(
+ caller_context,
+ purpose="--same-scope",
+ help_command="vibe agent run --help",
+ )
+ return _scope_id_from_session_id(caller_session_id, help_command="vibe agent run --help")
+ return None
+
+
+def _resolve_definition_scope_key(args, *, caller_context, help_command: str) -> Optional[str]:
+ raw_scope_id = (getattr(args, "scope_id", None) or "").strip()
+ same_scope = bool(getattr(args, "same_scope", False))
+ legacy_deliver_key = (getattr(args, "deliver_key", None) or "").strip()
+ if raw_scope_id and same_scope:
+ raise TaskCliError(
+ "use either --same-scope or --scope-id, not both",
+ code="conflicting_scope_target",
+ hint="Use --same-scope to reuse the caller scope, or --scope-id to place the new Session explicitly.",
+ help_command=help_command,
+ )
+ if legacy_deliver_key and (raw_scope_id or same_scope):
+ raise TaskCliError(
+ "use either legacy --deliver-key or the new scope placement flags, not both",
+ code="conflicting_scope_target",
+ hint="Use --scope-id or --same-scope for new Agent-facing commands.",
+ help_command=help_command,
+ )
+ if raw_scope_id:
+ return _validate_existing_scope_id(raw_scope_id, help_command=help_command).session_scope
+ if same_scope:
+ caller_session_id = _require_caller_session_id(
+ caller_context,
+ purpose="--same-scope",
+ help_command=help_command,
+ )
+ return _scope_id_from_session_id(caller_session_id, help_command=help_command)
+ if legacy_deliver_key:
+ return _parse_validated_session_key(legacy_deliver_key, help_command=help_command).session_scope
+ return None
+
+
+def _definition_metadata_with_scope(
+ caller_context,
+ *,
+ scope_id: Optional[str],
+ session_workdir: Optional[str] = None,
+) -> dict:
+ metadata = _definition_creation_metadata_from_caller(caller_context)
+ if scope_id:
+ metadata["session_scope_id"] = scope_id
+ if session_workdir:
+ metadata["session_workdir"] = session_workdir
+ return metadata
+
+
+def _scope_id_payload_from_session(session_id: Optional[str]) -> Optional[str]:
+ if not session_id:
+ return None
+ try:
+ return resolve_session_id_target(session_id).session_key.to_key(include_thread=False)
+ except ValueError:
+ return None
+
+
+def _validate_callback_session_id(session_id: str, *, help_command: str) -> None:
+ try:
+ resolve_session_id_target(session_id)
+ except ValueError as exc:
+ raise TaskCliError(
+ str(exc),
+ code="invalid_session_id",
+ hint="Pass an existing Agent Session ID as the callback target.",
+ help_command=help_command,
+ details={"session_id": session_id},
+ ) from exc
+
+
+def _resolve_runs_list_session_filter(args) -> Optional[str]:
+ explicit_session_id = (getattr(args, "session_id", None) or "").strip()
+ current_session = bool(getattr(args, "current_session", False))
+ if explicit_session_id and current_session:
+ raise TaskCliError(
+ "use either --session-id or --current-session, not both",
+ code="conflicting_session_filter",
+ hint="Use --current-session to resolve AVIBE_SESSION_ID, or pass a specific --session-id.",
+ help_command="vibe runs list --help",
+ )
+ if explicit_session_id:
+ return explicit_session_id
+ if current_session:
+ return _require_caller_session_id(
+ caller_context_from_env(),
+ purpose="--current-session",
+ help_command="vibe runs list --help",
+ )
+ return None
+
+
def _validate_delivery_args(
*,
session_key: str,
@@ -1422,6 +1631,38 @@ def _validate_delivery_args(
return session_target, delivery_target
+def _validate_delivery_override_for_target(
+ session_target,
+ *,
+ post_to: Optional[str],
+ deliver_key: Optional[str],
+ help_command: str,
+):
+ delivery_target = None
+ if deliver_key:
+ delivery_target = _parse_validated_session_key(deliver_key, help_command=help_command)
+ if delivery_target.platform != session_target.platform:
+ raise TaskCliError(
+ "--deliver-key must use the same platform as the session target",
+ code="invalid_delivery_target",
+ hint="Keep session memory and delivery on the same IM platform. Change only the channel, user, or thread target.",
+ help_command=help_command,
+ details={
+ "session_platform": session_target.platform,
+ "delivery_platform": delivery_target.platform,
+ },
+ )
+ elif post_to == "thread" and not session_target.thread_id:
+ raise TaskCliError(
+ "--post-to thread requires a thread-bound session target",
+ code="invalid_delivery_target",
+ hint="Use a thread-bound Agent Session ID, or keep delivery following the created Session target.",
+ help_command=help_command,
+ details={"post_to": post_to},
+ )
+ return session_target, delivery_target
+
+
def _collect_target_warnings(*targets) -> list[dict]:
from core.services import settings as settings_service
@@ -1475,9 +1716,12 @@ def _resolve_scope_routing_target(session_key: str) -> _ScopeRoutingTarget:
if not session_key:
return _ScopeRoutingTarget(None)
try:
- parsed = parse_session_key(session_key)
+ parsed = parse_scope_id(session_key)
except ValueError:
- return _ScopeRoutingTarget(None)
+ try:
+ parsed = parse_session_key(session_key)
+ except ValueError:
+ return _ScopeRoutingTarget(None)
scope_id = make_scope_id(parsed.platform, parsed.scope_type, parsed.scope_id)
_ensure_cli_sqlite_state()
engine = create_sqlite_engine(paths.get_sqlite_state_path())
@@ -1512,23 +1756,33 @@ def _resolve_agent_for_target(
requested = store.require_enabled(agent_name) if agent_name else None
if session_id:
target = resolve_session_id_target(session_id)
- resolved = requested
- if resolved is None and target.agent_name:
- resolved = store.require_enabled(target.agent_name)
- if resolved is not None and target.agent_backend and resolved.backend != target.agent_backend:
+ session_agent = store.require_enabled(target.agent_name) if target.agent_name else None
+ if requested is not None and session_agent is not None and requested.name != session_agent.name:
+ raise TaskCliError(
+ "agent does not match the existing session agent",
+ code="agent_session_agent_mismatch",
+ hint="Omit --agent when continuing an existing Session, or pass the same Agent name already bound to that Session.",
+ details={
+ "agent": requested.name,
+ "session_id": session_id,
+ "session_agent": session_agent.name,
+ },
+ help_command=help_command,
+ )
+ if requested is not None and target.agent_backend and requested.backend != target.agent_backend:
raise TaskCliError(
"agent backend does not match the existing session backend",
code="agent_session_backend_mismatch",
hint="Use an Agent with the same backend as the Session, or create a new Session.",
details={
- "agent": resolved.name,
- "agent_backend": resolved.backend,
+ "agent": requested.name,
+ "agent_backend": requested.backend,
"session_id": session_id,
"session_backend": target.agent_backend,
},
help_command=help_command,
)
- return resolved
+ return session_agent or requested
if requested is not None:
return requested
@@ -1778,6 +2032,7 @@ def cmd_task_add(args):
help_command="vibe task add --help",
allow_caller_session_default=caller_context is not None,
)
+ scope_key = _resolve_definition_scope_key(args, caller_context=caller_context, help_command="vibe task add --help")
message = _resolve_prompt_input(
args,
help_command="vibe task add --help",
@@ -1788,25 +2043,33 @@ def cmd_task_add(args):
required=session_policy == "existing",
help_command="vibe task add --help",
)
+ cwd = _resolve_definition_session_cwd(
+ explicit_cwd=getattr(args, "cwd", None),
+ existing_cwd=None,
+ session_policy=session_policy,
+ help_command="vibe task add --help",
+ )
agent = _resolve_agent_for_target(
agent_name=getattr(args, "agent", None),
session_id=session_id,
- session_key=session_key or getattr(args, "deliver_key", None) or "",
+ session_key=session_key or scope_key or "",
help_command="vibe task add --help",
)
agent_name = agent.name if agent else None
if session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
- deliver_key=args.deliver_key,
+ deliver_key=scope_key or "",
+ workdir=cwd,
help_command="vibe task add --help",
)
- validation_session_key = session_key or (args.deliver_key if session_policy == "create_per_run" else "")
- session_target, delivery_target = _validate_delivery_args(
+ session_target, delivery_target = _validate_definition_delivery_target(
+ session_policy=session_policy,
session_id=session_id,
- session_key=validation_session_key,
+ session_key=session_key,
post_to=getattr(args, "post_to", None),
deliver_key=getattr(args, "deliver_key", None),
+ scope_key=scope_key,
help_command="vibe task add --help",
)
timezone_name = args.timezone or _default_timezone_name()
@@ -1845,9 +2108,10 @@ def cmd_task_add(args):
schedule_type="cron",
agent_name=agent_name,
session_policy=session_policy,
+ cwd=cwd,
cron=args.cron,
timezone_name=timezone_name,
- metadata=_definition_creation_metadata_from_caller(caller_context),
+ metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),
)
else:
try:
@@ -1871,9 +2135,10 @@ def cmd_task_add(args):
schedule_type="at",
agent_name=agent_name,
session_policy=session_policy,
+ cwd=cwd,
run_at=run_at,
timezone_name=timezone_name,
- metadata=_definition_creation_metadata_from_caller(caller_context),
+ metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),
)
warnings = _collect_target_warnings(session_target, delivery_target)
task_payload = _task_payload(task)
@@ -1980,14 +2245,33 @@ def cmd_task_update(args):
)
if getattr(args, "reset_delivery", False) and (
- getattr(args, "post_to", None) is not None or getattr(args, "deliver_key", None) is not None
+ getattr(args, "post_to", None) is not None
+ or getattr(args, "deliver_key", None) is not None
+ or getattr(args, "scope_id", None) is not None
+ or bool(getattr(args, "same_scope", False))
):
raise TaskCliError(
"use either --reset-delivery or a new delivery flag, not both",
code="conflicting_delivery_target",
- hint="Pass --reset-delivery to clear delivery overrides, or pass --post-to/--deliver-key to replace them.",
+ hint="Pass --reset-delivery to clear delivery overrides, or pass --post-to/--scope-id/--same-scope to replace them.",
help_command="vibe task update --help",
)
+ caller_context = caller_context_from_env()
+ scope_arg_present = (getattr(args, "scope_id", None) is not None) or bool(getattr(args, "same_scope", False))
+ if scope_arg_present and not (
+ bool(getattr(args, "create_session", False)) or bool(getattr(args, "create_session_per_run", False))
+ ):
+ raise TaskCliError(
+ "scope placement flags only apply when creating Sessions",
+ code="scope_without_session_creation",
+ hint="Use --create-session or --create-session-per-run with --scope-id/--same-scope, or omit the scope placement flag.",
+ help_command="vibe task update --help",
+ )
+ requested_scope_key = _resolve_definition_scope_key(
+ args,
+ caller_context=caller_context,
+ help_command="vibe task update --help",
+ )
session_id_update, session_key_update = _resolve_session_target_args(
args,
required=False,
@@ -2017,6 +2301,11 @@ def cmd_task_update(args):
else:
post_to = task.post_to
deliver_key = task.deliver_key
+ metadata = dict(task.metadata or {})
+ if requested_scope_key:
+ metadata["session_scope_id"] = requested_scope_key
+ elif scope_arg_present:
+ metadata.pop("session_scope_id", None)
if getattr(args, "name", None) is not None and getattr(args, "clear_name", False):
raise TaskCliError(
@@ -2115,18 +2404,45 @@ def cmd_task_update(args):
next_schedule_type=schedule_type,
help_command="vibe task update --help",
)
- if session_policy in {"create_once", "create_per_run"} and not deliver_key:
+ explicit_cwd = getattr(args, "cwd", None)
+ _reject_inert_create_once_cwd_update(
+ explicit_cwd=explicit_cwd,
+ current_policy=task.session_policy,
+ current_session_id=task.session_id,
+ create_session=bool(getattr(args, "create_session", False)),
+ help_command="vibe task update --help",
+ )
+ if session_policy == "existing":
+ cwd = _resolve_definition_session_cwd(
+ explicit_cwd=explicit_cwd,
+ existing_cwd=None,
+ session_policy=session_policy,
+ help_command="vibe task update --help",
+ )
+ elif explicit_cwd is not None:
+ cwd = _resolve_definition_session_cwd(
+ explicit_cwd=explicit_cwd,
+ existing_cwd=None,
+ session_policy=session_policy,
+ help_command="vibe task update --help",
+ )
+ elif getattr(args, "create_session", False) or getattr(args, "create_session_per_run", False):
+ cwd = task.cwd or os.getcwd()
+ else:
+ cwd = task.cwd
+ scope_key = requested_scope_key or str(metadata.get("session_scope_id") or "").strip() or _legacy_scope_key_from_target(deliver_key)
+ if session_policy in {"create_once", "create_per_run"} and not scope_key:
raise TaskCliError(
- "--deliver-key is required when a stored definition creates sessions",
+ "--scope-id or --same-scope is required when a stored definition creates sessions",
code="missing_delivery_target",
- hint="Pass the Scope ID that owns the new Session.",
+ hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",
help_command="vibe task update --help",
)
if agent_name is None and session_policy != "existing":
agent = _resolve_agent_for_target(
agent_name=None,
session_id=None,
- session_key=deliver_key or "",
+ session_key=scope_key,
help_command="vibe task update --help",
)
agent_name = agent.name if agent else None
@@ -2143,16 +2459,24 @@ def cmd_task_update(args):
):
session_id = _reserve_definition_session(
agent_name=agent_name,
- deliver_key=deliver_key or "",
+ deliver_key=scope_key,
+ workdir=cwd,
help_command="vibe task update --help",
)
session_key = ""
+ if session_policy == "existing":
+ metadata.pop("session_workdir", None)
+ elif cwd:
+ metadata["session_workdir"] = cwd
+ else:
+ metadata.pop("session_workdir", None)
session_target, delivery_target = _validate_definition_update_delivery_target(
session_policy=session_policy,
session_id=session_id,
session_key=session_key,
post_to=post_to,
deliver_key=deliver_key,
+ scope_key=scope_key,
help_command="vibe task update --help",
)
@@ -2166,9 +2490,11 @@ def cmd_task_update(args):
"schedule_type": schedule_type,
"post_to": post_to,
"deliver_key": deliver_key,
+ "cwd": cwd,
"cron": cron,
"run_at": run_at,
"timezone": timezone_name,
+ "metadata": metadata,
}
current = {
"name": task.name,
@@ -2180,15 +2506,17 @@ def cmd_task_update(args):
"schedule_type": task.schedule_type,
"post_to": task.post_to,
"deliver_key": task.deliver_key,
+ "cwd": task.cwd,
"cron": task.cron,
"run_at": task.run_at,
"timezone": task.timezone,
+ "metadata": task.metadata,
}
if changes == current:
raise TaskCliError(
"no task fields were changed",
code="no_task_changes",
- hint="Pass at least one field to update, such as --name, --cron, --message, --session-id, or --deliver-key.",
+ hint="Pass at least one field to update, such as --name, --cron, --message, --session-id, or --scope-id.",
help_command="vibe task update --help",
details={"task_id": args.task_id},
)
@@ -2204,9 +2532,12 @@ def cmd_task_update(args):
session_policy=session_policy,
post_to=post_to,
deliver_key=deliver_key,
+ cwd=cwd,
+ update_cwd=True,
cron=cron,
run_at=run_at,
timezone_name=timezone_name,
+ metadata=metadata,
)
warnings = _collect_target_warnings(session_target, delivery_target)
task_payload = _task_payload(updated)
@@ -2686,8 +3017,13 @@ def cmd_agent_import(args):
def _validate_run_session_policy(args, *, help_command: str) -> str:
session_id = (getattr(args, "session_id", None) or "").strip()
fork_session = (getattr(args, "fork_session", None) or "").strip()
+ fork_self = bool(getattr(args, "fork_self", False))
create_session = bool(getattr(args, "create_session", False))
create_per_run = bool(getattr(args, "create_session_per_run", False))
+ same_scope = bool(getattr(args, "same_scope", False))
+ scope_id = (getattr(args, "scope_id", None) or "").strip()
+ deliver_key = (getattr(args, "deliver_key", None) or "").strip()
+ agent_name = (getattr(args, "agent", None) or "").strip()
if bool(getattr(args, "async_run", False)) and getattr(args, "wait_timeout", None) is not None:
raise TaskCliError(
"use --async or --wait-timeout, not both",
@@ -2702,37 +3038,58 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:
hint="Pass --callback-session-id to receive a follow-up, or --no-callback to intentionally inspect the run later.",
help_command=help_command,
)
- if (getattr(args, "callback_session_id", None) or "").strip() and not bool(getattr(args, "async_run", False)):
+ if same_scope and scope_id:
+ raise TaskCliError(
+ "use either --same-scope or --scope-id, not both",
+ code="conflicting_scope_placement",
+ hint="Use --same-scope to reuse the caller/source scope, or --scope-id to place the new Session explicitly.",
+ help_command=help_command,
+ )
+ if deliver_key and (same_scope or scope_id):
+ raise TaskCliError(
+ "use either legacy --deliver-key or the new scope placement flags, not both",
+ code="conflicting_scope_placement",
+ hint="Use --scope-id or --same-scope for new Agent-facing commands.",
+ help_command=help_command,
+ )
+ if fork_self and fork_session:
raise TaskCliError(
- "--callback-session-id requires --async",
- code="callback_requires_async",
- hint="Callback delivery happens after an asynchronous run completes.",
+ "use either --fork-self or --fork-session, not both",
+ code="conflicting_session_policy",
+ hint="Use --fork-self from inside an Avibe Agent shell, or pass an explicit --fork-session.",
help_command=help_command,
)
- if bool(getattr(args, "no_callback", False)) and not bool(getattr(args, "async_run", False)):
+ if fork_self and session_id:
raise TaskCliError(
- "--no-callback requires --async",
- code="no_callback_requires_async",
- hint="Only asynchronous runs need an explicit callback or no-callback policy.",
+ "use --fork-self without --session-id",
+ code="conflicting_session_policy",
+ hint="--fork-self resolves the source Session from AVIBE_SESSION_ID.",
help_command=help_command,
)
- if fork_session and (session_id or create_session or create_per_run):
+ if (fork_session or fork_self) and (session_id or create_session or create_per_run):
raise TaskCliError(
- "use --fork-session without --session-id or session creation flags",
+ "use fork without --session-id or session creation flags",
code="conflicting_session_policy",
hint="Fork creates a new Session from the source Session.",
help_command=help_command,
)
- if not fork_session and (
+ if not (fork_session or fork_self) and (
(getattr(args, "model", None) or "").strip()
or (getattr(args, "reasoning_effort", None) or "").strip()
):
raise TaskCliError(
- "--model and --reasoning-effort are only valid with --fork-session",
+ "--model and --reasoning-effort are only valid with forked Sessions",
code="fork_override_without_fork",
hint="Use --agent, --model, and --reasoning-effort as overrides when forking a Session.",
help_command=help_command,
)
+ if session_id and (same_scope or scope_id):
+ raise TaskCliError(
+ "scope placement flags only apply when creating a new Session",
+ code="scope_with_existing_session",
+ hint="An existing --session-id keeps its original scope.",
+ help_command=help_command,
+ )
if session_id and (create_session or create_per_run):
raise TaskCliError(
"use either --session-id or --create-session, not both",
@@ -2752,7 +3109,7 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:
hint="Use --create-session for a one-shot agent run.",
help_command=help_command,
)
- if fork_session:
+ if fork_session or fork_self:
return "fork"
if create_session:
return "create"
@@ -2773,6 +3130,8 @@ def _validate_definition_session_policy(
create_session = bool(getattr(args, "create_session", False))
create_per_run = bool(getattr(args, "create_session_per_run", False))
deliver_key = (getattr(args, "deliver_key", None) or "").strip()
+ scope_id = (getattr(args, "scope_id", None) or "").strip()
+ same_scope = bool(getattr(args, "same_scope", False))
specified = sum(1 for value in (bool(session_id or session_key), create_session, create_per_run) if value)
if specified > 1:
raise TaskCliError(
@@ -2788,11 +3147,18 @@ def _validate_definition_session_policy(
hint="Use --create-session for a one-shot task because it only runs once.",
help_command=help_command,
)
- if (create_session or create_per_run) and not deliver_key:
+ if (scope_id or same_scope) and not (create_session or create_per_run):
+ raise TaskCliError(
+ "scope placement flags only apply when creating Sessions",
+ code="scope_without_session_creation",
+ hint="Use --create-session or --create-session-per-run with --scope-id/--same-scope, or omit the scope placement flag.",
+ help_command=help_command,
+ )
+ if (create_session or create_per_run) and not (deliver_key or scope_id or same_scope):
raise TaskCliError(
- "--deliver-key is required when a stored definition creates sessions",
+ "--scope-id or --same-scope is required when a stored definition creates sessions",
code="missing_delivery_target",
- hint="Pass the Scope ID that owns the new Session.",
+ hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",
help_command=help_command,
)
if create_session:
@@ -2807,7 +3173,7 @@ def _validate_definition_session_policy(
"one session policy is required",
code="missing_session_policy",
hint=(
- "Use --session-id to continue a Session, or --create-session with --deliver-key to create one. "
+ "Use --session-id to continue a Session, or --create-session with --same-scope/--scope-id to create one. "
"Inside an Avibe Agent shell, Avibe can default this to the caller Session from AVIBE_SESSION_ID."
),
help_command=help_command,
@@ -2826,6 +3192,8 @@ def _definition_session_policy_for_update(
create_per_run = bool(getattr(args, "create_session_per_run", False))
session_id = (getattr(args, "session_id", None) or "").strip()
session_key = (getattr(args, "session_key", None) or "").strip()
+ scope_id = (getattr(args, "scope_id", None) or "").strip()
+ same_scope = bool(getattr(args, "same_scope", False))
if create_session and create_per_run:
raise TaskCliError(
"use either --create-session or --create-session-per-run, not both",
@@ -2845,6 +3213,13 @@ def _definition_session_policy_for_update(
hint="Use --create-session for a one-shot task because it only runs once.",
help_command=help_command,
)
+ if (scope_id or same_scope) and not (create_session or create_per_run):
+ raise TaskCliError(
+ "scope placement flags only apply when creating Sessions",
+ code="scope_without_session_creation",
+ hint="Use --create-session or --create-session-per-run with --scope-id/--same-scope, or omit the scope placement flag.",
+ help_command=help_command,
+ )
if create_session:
return "create_once"
if create_per_run:
@@ -2861,6 +3236,25 @@ def _definition_session_policy_for_update(
return current_policy or "existing"
+def _reject_inert_create_once_cwd_update(
+ *,
+ explicit_cwd: Optional[str],
+ current_policy: Optional[str],
+ current_session_id: Optional[str],
+ create_session: bool,
+ help_command: str,
+) -> None:
+ if explicit_cwd is None or create_session:
+ return
+ if current_policy == "create_once" and current_session_id:
+ raise TaskCliError(
+ "--cwd cannot update an already-created reusable Session",
+ code="cwd_with_existing_session",
+ hint="Pass --create-session with --cwd to reserve a replacement Session, or omit --cwd because the existing Session keeps its own workdir.",
+ help_command=help_command,
+ )
+
+
def _validate_definition_update_delivery_target(
*,
session_policy: str,
@@ -2868,12 +3262,48 @@ def _validate_definition_update_delivery_target(
session_key: str,
post_to: Optional[str],
deliver_key: Optional[str],
+ scope_key: Optional[str],
+ help_command: str,
+):
+ return _validate_definition_delivery_target(
+ session_policy=session_policy,
+ session_id=session_id,
+ session_key=session_key,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ scope_key=scope_key,
+ help_command=help_command,
+ )
+
+
+def _validate_definition_delivery_target(
+ *,
+ session_policy: str,
+ session_id: Optional[str],
+ session_key: str,
+ post_to: Optional[str],
+ deliver_key: Optional[str],
+ scope_key: Optional[str],
help_command: str,
):
- validation_session_key = session_key or (deliver_key if session_policy == "create_per_run" else "")
+ if session_policy == "create_per_run":
+ if not scope_key:
+ raise TaskCliError(
+ "--scope-id or --same-scope is required when a stored definition creates sessions",
+ code="missing_delivery_target",
+ hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",
+ help_command=help_command,
+ )
+ session_target = _parse_validated_scope_id(scope_key, help_command=help_command)
+ return _validate_delivery_override_for_target(
+ session_target,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ help_command=help_command,
+ )
return _validate_delivery_args(
session_id=session_id,
- session_key=validation_session_key,
+ session_key=session_key,
post_to=post_to,
deliver_key=deliver_key,
help_command=help_command,
@@ -2881,24 +3311,20 @@ def _validate_definition_update_delivery_target(
def _resolve_run_cwd(args, *, session_policy: str, help_command: str) -> Optional[str]:
- """Working directory for a session this run RESERVES; None = scope snapshot.
-
- An explicit ``--cwd`` must exist and always wins. Without it, a private
- (no ``--deliver-key``) reservation follows the CLI invocation's cwd — the
- caller stands in a concrete directory, which IS the natural context, like
- every other CLI tool. A ``--deliver-key`` reservation keeps the target
- scope's configured workdir (returning None defers to the scope snapshot in
- ``create_agent_session_row``): the scope's binding is the deliberate choice
- there, not wherever the CLI happens to run. ``--session-id`` reserves
- nothing — an existing session keeps its workdir — so ``--cwd`` is an error.
+ """Working directory for a session this run RESERVES.
+
+ An explicit ``--cwd`` must exist and always wins for blank session creation.
+ Without it, new blank sessions follow the CLI invocation's cwd, including
+ private/background and same-scope/scope-id placements.
+ Existing and forked sessions keep their own cwd, so ``--cwd`` is an error.
"""
raw = (getattr(args, "cwd", None) or "").strip()
- if session_policy == "existing":
+ if session_policy in {"existing", "fork"}:
if raw:
raise TaskCliError(
- "--cwd only applies when this run creates a session",
+ "--cwd only applies when this run creates a blank session",
code="cwd_with_existing_session",
- hint="An existing --session-id keeps its own working directory.",
+ hint="Existing and forked Sessions keep their own working directory.",
help_command=help_command,
)
return None
@@ -2912,11 +3338,31 @@ def _resolve_run_cwd(args, *, session_policy: str, help_command: str) -> Optiona
help_command=help_command,
)
return resolved
- if (getattr(args, "deliver_key", None) or "").strip():
- return None
return os.getcwd()
+def _resolve_definition_session_cwd(
+ *,
+ explicit_cwd: Optional[str],
+ existing_cwd: Optional[str],
+ session_policy: str,
+ help_command: str,
+) -> Optional[str]:
+ raw = (explicit_cwd or "").strip()
+ if session_policy == "existing":
+ if raw:
+ raise TaskCliError(
+ "--cwd only applies when this definition creates new Sessions",
+ code="cwd_with_existing_session",
+ hint="An existing target Session keeps its own working directory.",
+ help_command=help_command,
+ )
+ return None
+ if raw:
+ return _resolve_existing_cwd(raw, help_command=help_command, code="cwd_not_found", label="task")
+ return existing_cwd or os.getcwd()
+
+
def _session_creation_metadata_from_caller(caller_context) -> dict:
if caller_context is None:
return {}
@@ -2939,41 +3385,57 @@ def _agent_run_source_from_caller(caller_context) -> tuple[str, Optional[str], O
return "agent", caller_context.session_id, caller_context.run_id, metadata
-def _resolve_async_callback_session_id(args, caller_context, *, target_session_id: Optional[str] = None):
+def _resolve_callback_session_id(args, caller_context, *, target_session_id: Optional[str] = None):
explicit_callback = (getattr(args, "callback_session_id", None) or "").strip() or None
no_callback = bool(getattr(args, "no_callback", False))
- if not bool(getattr(args, "async_run", False)):
- return explicit_callback, None
+ is_async = bool(getattr(args, "async_run", False))
if explicit_callback:
- return explicit_callback, None
+ return explicit_callback, {
+ "code": "callback_explicit",
+ "message": (
+ "Callback route recorded for this Agent Run."
+ if not is_async
+ else "Async callback will be sent to the explicit Session."
+ ),
+ "callback_session_id": explicit_callback,
+ }
if no_callback:
+ message = (
+ "Started async Agent Run without a callback. This run will not post its final result back into a "
+ "Session automatically. Track it with `vibe runs show <run-id>` or by polling/listing runs for the "
+ "target Session. To receive a follow-up message next time, use `--callback-session-id <session-id>` "
+ "or run from a resolved caller context so Avibe can default the callback to the current Session."
+ )
+ if not is_async:
+ message = (
+ "Recorded an explicit no-callback policy. This synchronous run will not send a callback if it later "
+ "detaches into an asynchronous background run."
+ )
return None, {
"code": "async_run_without_callback",
- "message": (
- "Started async Agent Run without a callback. This run will not post its final result back into a "
- "Session automatically. Track it with `vibe runs show <run-id>` or by polling/listing runs for the "
- "target Session. To receive a follow-up message next time, use `--callback-session-id <session-id>` "
- "or run from a resolved caller context so Avibe can default the callback to the current Session."
- ),
+ "message": message,
}
if caller_context is not None:
caller_session_id = caller_context.session_id
if target_session_id and target_session_id == caller_session_id:
- raise TaskCliError(
- "This async Agent Run targets the caller Session itself, so Avibe cannot safely default a callback.",
- code="self_callback_requires_explicit_policy",
- hint=(
- "Pass --no-callback when continuing the same Session asynchronously, or pass "
- "--callback-session-id <session-id> to send the final result to a different caller Session. "
- "Default callbacks are only inferred when the delegated run targets a different Session."
+ return None, {
+ "code": "async_self_run_without_callback",
+ "message": (
+ "Started Agent Run on the caller Session without a callback. "
+ "The target Session will receive the run result directly, so Avibe did not create a duplicate callback turn."
),
- help_command="vibe agent run --help",
- )
+ }
return caller_context.session_id, {
"code": "callback_defaulted_to_caller_session",
- "message": "Async callback defaulted to the caller Session from AVIBE_SESSION_ID.",
+ "message": (
+ "Async callback defaulted to the caller Session from AVIBE_SESSION_ID."
+ if is_async
+ else "Callback route defaulted to the caller Session from AVIBE_SESSION_ID."
+ ),
"callback_session_id": caller_session_id,
}
+ if not is_async:
+ return None, None
raise TaskCliError(
"This async Agent Run has no callback target.",
code="missing_async_callback",
@@ -2991,18 +3453,20 @@ def _resolve_async_callback_session_id(args, caller_context, *, target_session_i
def _reserve_cli_session(
*,
agent,
- deliver_key: Optional[str],
+ scope_key: Optional[str],
workdir: Optional[str] = None,
metadata: Optional[dict] = None,
+ session_anchor_target=None,
) -> str:
# Route through ``core.services.sessions`` so the CLI shares the same
# business API as the UI server and the future N3 internal endpoint;
# see docs/plans/workbench-dispatch-architecture.md §6 (C2).
from core.services import sessions as sessions_service
- if deliver_key:
- target = _parse_validated_session_key(deliver_key, help_command="vibe agent run --help")
- session_anchor = session_anchor_for_target(target)
+ if scope_key:
+ target = _parse_validated_scope_id(scope_key, help_command="vibe agent run --help")
+ anchor_target = session_anchor_target or target
+ session_anchor = _session_anchor_with_suffix(anchor_target, suffix="run")
session_id = sessions_service.reserve_agent_session(
scope_key=target.session_scope,
agent_backend=agent.backend,
@@ -3012,7 +3476,7 @@ def _reserve_cli_session(
model=agent.model,
reasoning_effort=agent.reasoning_effort,
workdir=workdir,
- metadata=metadata,
+ metadata={"scope_placement": "explicit", **dict(metadata or {})},
)
else:
platform = _primary_platform()
@@ -3037,12 +3501,25 @@ def _reserve_cli_session(
return session_id
+def _session_anchor_with_suffix(target, *, suffix: str) -> str:
+ return f"{session_anchor_for_target(target)}:{suffix}_{uuid4().hex[:12]}"
+
+
+def _sync_run_detached(run_payload: dict) -> bool:
+ return (
+ run_payload.get("wait_state") == "detached"
+ or run_payload.get("handoff_reason") == "wait_limit_reached"
+ or normalize_run_status(run_payload.get("status")) not in {"succeeded", "failed", "canceled"}
+ )
+
+
def _reserve_forked_cli_session(
*,
source_session_id: str,
agent_name: Optional[str],
model: Optional[str],
reasoning_effort: Optional[str],
+ scope_key: Optional[str],
):
from core.services.session_fork import SessionForkError, reserve_forked_session
@@ -3052,6 +3529,7 @@ def _reserve_forked_cli_session(
agent_name=agent_name or None,
model=model,
reasoning_effort=reasoning_effort,
+ scope_id=scope_key,
db_path=paths.get_sqlite_state_path(),
)
except SessionForkError as exc:
@@ -3064,10 +3542,19 @@ def _reserve_forked_cli_session(
) from exc
-def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str, help_command: str) -> str:
+def _reserve_definition_session(
+ *,
+ agent_name: Optional[str],
+ deliver_key: str,
+ help_command: str,
+ workdir: Optional[str] = None,
+) -> str:
from core.services import sessions as sessions_service
- target = _parse_validated_session_key(deliver_key, help_command=help_command)
+ try:
+ target = _parse_validated_scope_id(deliver_key, help_command=help_command)
+ except TaskCliError:
+ target = _parse_validated_session_key(deliver_key, help_command=help_command)
agent = _resolve_agent_for_session_reservation(
agent_name=agent_name,
deliver_key=deliver_key,
@@ -3081,7 +3568,7 @@ def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str,
help_command=help_command,
)
agent_backend = agent.backend
- session_anchor = session_anchor_for_target(target)
+ session_anchor = _session_anchor_with_suffix(target, suffix="definition")
session_id = sessions_service.reserve_agent_session(
scope_key=target.session_scope,
agent_backend=agent_backend,
@@ -3090,6 +3577,7 @@ def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str,
agent_name=agent.name if agent else None,
model=agent.model if agent else None,
reasoning_effort=agent.reasoning_effort if agent else None,
+ workdir=workdir,
)
if not session_id:
raise TaskCliError(
@@ -3117,23 +3605,39 @@ def cmd_agent_run(args):
hint="Pass --agent with the Avibe Agent name to run.",
help_command="vibe agent run --help",
)
- if session_policy in {"none", "fork"} and (args.deliver_key or args.post_to):
+ source_session_id = (args.fork_session or "").strip() or None
+ if bool(getattr(args, "fork_self", False)):
+ source_session_id = _require_caller_session_id(
+ caller_context,
+ purpose="--fork-self",
+ help_command="vibe agent run --help",
+ )
+ setattr(args, "fork_session", source_session_id)
+ if session_policy == "none" and (args.deliver_key or args.post_to):
raise TaskCliError(
- "delivery options require --session-id or --create-session",
+ "delivery options require an explicit Session target",
code="delivery_target_without_session_policy",
- hint="Use --create-session --deliver-key <scope-id> when a new delivered Session should be created.",
+ hint="Use --same-scope or --scope-id for new Session placement. Use --post-to only with an existing target.",
help_command="vibe agent run --help",
)
- session_id = (args.session_id or "").strip() or None
- session_key = ""
- if session_policy == "fork" and (args.cwd or "").strip():
+ if session_policy == "fork" and args.post_to:
raise TaskCliError(
- "--cwd only applies when this run creates a blank session",
- code="cwd_with_fork_session",
- hint="A fork copies the source Session working directory.",
+ "delivery options require an existing Session target",
+ code="delivery_target_without_session_policy",
+ hint="Fork creates a new Session. Use scope placement flags for where it lives; callback controls where results return.",
help_command="vibe agent run --help",
)
+ session_id = (args.session_id or "").strip() or None
+ session_key = ""
run_cwd = _resolve_run_cwd(args, session_policy=session_policy, help_command="vibe agent run --help")
+ scope_key = _resolve_agent_run_scope_key(args, caller_context=caller_context, source_session_id=source_session_id)
+ legacy_reservation_target = None
+ if not scope_key and (args.deliver_key or "").strip():
+ # Hidden legacy compatibility: external docs and prompts should use
+ # --scope-id/--same-scope, while old callers still map into the same
+ # internal placement field.
+ legacy_reservation_target = _parse_validated_session_key(args.deliver_key, help_command="vibe agent run --help")
+ scope_key = legacy_reservation_target.session_scope
agent = _agent_store().require_enabled(agent_name) if agent_name else None
fork_result = None
session_metadata = _session_creation_metadata_from_caller(caller_context)
@@ -3154,30 +3658,34 @@ def cmd_agent_run(args):
deliver_key=args.deliver_key,
help_command="vibe agent run --help",
)
- elif session_policy == "create" and args.deliver_key:
- _parse_validated_session_key(args.deliver_key, help_command="vibe agent run --help")
- callback_session_id, callback_notice = _resolve_async_callback_session_id(
- args,
- caller_context,
- target_session_id=session_id,
- )
+ callback_session_id, callback_notice = _resolve_callback_session_id(args, caller_context, target_session_id=session_id)
if callback_session_id:
- resolve_session_id_target(callback_session_id)
+ _validate_callback_session_id(callback_session_id, help_command="vibe agent run --help")
+ legacy_deliver_key = args.deliver_key
+ if (getattr(args, "same_scope", False) or (getattr(args, "scope_id", None) or "").strip()) and legacy_deliver_key != scope_key:
+ legacy_deliver_key = None
if session_policy == "create":
session_id = _reserve_cli_session(
agent=agent,
- deliver_key=args.deliver_key,
+ scope_key=scope_key,
workdir=run_cwd,
metadata=session_metadata,
+ session_anchor_target=legacy_reservation_target,
)
elif session_policy == "none":
- session_id = _reserve_cli_session(agent=agent, deliver_key=None, workdir=run_cwd, metadata=session_metadata)
+ session_id = _reserve_cli_session(
+ agent=agent,
+ scope_key=scope_key,
+ workdir=run_cwd,
+ metadata=session_metadata,
+ )
elif session_policy == "fork":
fork_result = _reserve_forked_cli_session(
- source_session_id=(args.fork_session or "").strip(),
+ source_session_id=source_session_id or "",
agent_name=agent_name or None,
model=args.model,
reasoning_effort=args.reasoning_effort,
+ scope_key=scope_key,
)
session_id = fork_result.session_id
if agent_name:
@@ -3191,14 +3699,12 @@ def cmd_agent_run(args):
session_key=session_key,
help_command="vibe agent run --help",
)
- if (session_policy in {"create", "none"} or fork_result) and (
- session_policy != "none" or args.post_to or args.deliver_key
- ):
+ if (session_policy in {"create", "none"} or fork_result) and args.post_to:
_validate_delivery_args(
session_id=session_id,
session_key=session_key,
post_to=args.post_to,
- deliver_key=args.deliver_key,
+ deliver_key=None,
help_command="vibe agent run --help",
)
source_kind, source_actor, parent_run_id, provenance_metadata = _agent_run_source_from_caller(caller_context)
@@ -3220,14 +3726,16 @@ def cmd_agent_run(args):
session_key=session_key,
session_id=session_id,
post_to=args.post_to,
- deliver_key=args.deliver_key,
+ deliver_key=legacy_deliver_key,
message=message,
source_kind=source_kind,
source_actor=source_actor,
parent_run_id=parent_run_id,
callback_session_id=callback_session_id,
+ callback_active=bool(args.async_run),
metadata=provenance_metadata or None,
)
+ resolved_scope_id = _scope_id_payload_from_session(session_id)
payload = {
"accepted": True,
"request_type": request.request_type,
@@ -3236,7 +3744,8 @@ def cmd_agent_run(args):
"agent": agent.name if agent else None,
"session_policy": session_policy,
"session_id": session_id,
- "deliver_key": args.deliver_key,
+ "scope_id": resolved_scope_id,
+ "deliver_key": legacy_deliver_key,
"callback_session_id": callback_session_id,
"async": bool(args.async_run),
"caller_context": caller_context.to_metadata() if caller_context else None,
@@ -3247,6 +3756,7 @@ def cmd_agent_run(args):
"run_type": request.request_type,
"agent_name": agent.name if agent else None,
"session_id": session_id,
+ "scope_id": resolved_scope_id,
"callback_session_id": callback_session_id,
"source_kind": source_kind,
"source_actor": source_actor,
@@ -3258,7 +3768,11 @@ def cmd_agent_run(args):
if fork_result:
payload["run"]["forked_from_session_id"] = fork_result.fork.source_session_id
if not args.async_run:
- payload["run"] = _wait_for_run_result(request_store, request.id, wait_timeout=args.wait_timeout)
+ run_payload = _wait_for_run_result(request_store, request.id, wait_timeout=args.wait_timeout)
+ if callback_session_id and _sync_run_detached(run_payload):
+ request_store.mark_callback_pending(request.id)
+ run_payload["callback_status"] = "pending"
+ payload["run"] = run_payload
_print_cli_payload("agent_run", **payload)
return 0
except Exception as exc:
@@ -3303,7 +3817,7 @@ def cmd_runs_list(args):
run_type=getattr(args, "type", None),
agent_name=getattr(args, "agent", None),
agent_backend=getattr(args, "backend", None),
- session_id=getattr(args, "session_id", None),
+ session_id=_resolve_runs_list_session_filter(args),
definition_id=getattr(args, "definition_id", None),
created_after=created_after,
created_before=created_before,
@@ -3317,6 +3831,8 @@ def cmd_runs_list(args):
_add_optional_arg(command, "--agent", getattr(args, "agent", None))
_add_optional_arg(command, "--backend", getattr(args, "backend", None))
_add_optional_arg(command, "--session-id", getattr(args, "session_id", None))
+ if getattr(args, "current_session", False):
+ command.append("--current-session")
_add_optional_arg(command, "--definition-id", getattr(args, "definition_id", None))
_add_optional_arg(command, "--created-after", created_after)
_add_optional_arg(command, "--created-before", created_before)
@@ -5194,6 +5710,7 @@ def cmd_watch_add(args):
help_command="vibe watch add --help",
allow_caller_session_default=caller_context is not None,
)
+ scope_key = _resolve_definition_scope_key(args, caller_context=caller_context, help_command="vibe watch add --help")
command, shell_command = _resolve_watch_command(args, help_command="vibe watch add --help")
session_id, session_key = _resolve_session_target_args(
args,
@@ -5203,22 +5720,25 @@ def cmd_watch_add(args):
agent = _resolve_agent_for_target(
agent_name=getattr(args, "agent", None),
session_id=session_id,
- session_key=session_key or getattr(args, "deliver_key", None) or "",
+ session_key=session_key or scope_key or "",
help_command="vibe watch add --help",
)
agent_name = agent.name if agent else None
+ cwd = _resolve_watch_cwd(args.cwd, help_command="vibe watch add --help", default_to_invocation=True)
if session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
- deliver_key=args.deliver_key,
+ deliver_key=scope_key or "",
+ workdir=cwd,
help_command="vibe watch add --help",
)
- validation_session_key = session_key or (args.deliver_key if session_policy == "create_per_run" else "")
- session_target, delivery_target = _validate_delivery_args(
+ session_target, delivery_target = _validate_definition_delivery_target(
+ session_policy=session_policy,
session_id=session_id,
- session_key=validation_session_key,
+ session_key=session_key,
post_to=getattr(args, "post_to", None),
deliver_key=getattr(args, "deliver_key", None),
+ scope_key=scope_key,
help_command="vibe watch add --help",
)
@@ -5230,7 +5750,6 @@ def cmd_watch_add(args):
mode=mode,
help_command="vibe watch add --help",
)
- cwd = _resolve_watch_cwd(args.cwd, help_command="vibe watch add --help")
prefix = _normalize_task_name(getattr(args, "prefix", None))
message = _resolve_optional_message_input(
args,
@@ -5259,7 +5778,7 @@ def cmd_watch_add(args):
deliver_key=args.deliver_key,
agent_name=agent_name,
session_policy=session_policy,
- metadata=_definition_creation_metadata_from_caller(caller_context),
+ metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),
)
runtime_store = _watch_runtime_store()
watch, runtime_entry = _wait_for_watch_startup(store, runtime_store, watch.id)
@@ -5348,14 +5867,33 @@ def cmd_watch_update(args):
)
if getattr(args, "reset_delivery", False) and (
- getattr(args, "post_to", None) is not None or getattr(args, "deliver_key", None) is not None
+ getattr(args, "post_to", None) is not None
+ or getattr(args, "deliver_key", None) is not None
+ or getattr(args, "scope_id", None) is not None
+ or bool(getattr(args, "same_scope", False))
):
raise TaskCliError(
"use either --reset-delivery or a new delivery flag, not both",
code="conflicting_delivery_target",
- hint="Pass --reset-delivery to clear delivery overrides, or pass --post-to/--deliver-key to replace them.",
+ hint="Pass --reset-delivery to clear delivery overrides, or pass --post-to/--scope-id/--same-scope to replace them.",
+ help_command="vibe watch update --help",
+ )
+ caller_context = caller_context_from_env()
+ scope_arg_present = (getattr(args, "scope_id", None) is not None) or bool(getattr(args, "same_scope", False))
+ if scope_arg_present and not (
+ bool(getattr(args, "create_session", False)) or bool(getattr(args, "create_session_per_run", False))
+ ):
+ raise TaskCliError(
+ "scope placement flags only apply when creating Sessions",
+ code="scope_without_session_creation",
+ hint="Use --create-session or --create-session-per-run with --scope-id/--same-scope, or omit the scope placement flag.",
help_command="vibe watch update --help",
)
+ requested_scope_key = _resolve_definition_scope_key(
+ args,
+ caller_context=caller_context,
+ help_command="vibe watch update --help",
+ )
if getattr(args, "name", None) is not None and getattr(args, "clear_name", False):
raise TaskCliError(
"use either --name or --clear-name, not both",
@@ -5399,6 +5937,11 @@ def cmd_watch_update(args):
else:
post_to = watch.post_to
deliver_key = watch.deliver_key
+ metadata = dict(watch.metadata or {})
+ if requested_scope_key:
+ metadata["session_scope_id"] = requested_scope_key
+ elif scope_arg_present:
+ metadata.pop("session_scope_id", None)
command = list(watch.command)
shell_command = watch.shell_command
@@ -5475,18 +6018,19 @@ def cmd_watch_update(args):
next_schedule_type="watch",
help_command="vibe watch update --help",
)
- if session_policy in {"create_once", "create_per_run"} and not deliver_key:
+ scope_key = requested_scope_key or str(metadata.get("session_scope_id") or "").strip() or _legacy_scope_key_from_target(deliver_key)
+ if session_policy in {"create_once", "create_per_run"} and not scope_key:
raise TaskCliError(
- "--deliver-key is required when a stored definition creates sessions",
+ "--scope-id or --same-scope is required when a stored definition creates sessions",
code="missing_delivery_target",
- hint="Pass the Scope ID that owns the new Session.",
+ hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",
help_command="vibe watch update --help",
)
if agent_name is None and session_policy != "existing":
agent = _resolve_agent_for_target(
agent_name=None,
session_id=None,
- session_key=deliver_key or "",
+ session_key=scope_key,
help_command="vibe watch update --help",
)
agent_name = agent.name if agent else None
@@ -5503,16 +6047,22 @@ def cmd_watch_update(args):
):
session_id = _reserve_definition_session(
agent_name=agent_name,
- deliver_key=deliver_key or "",
+ deliver_key=scope_key,
+ workdir=cwd,
help_command="vibe watch update --help",
)
session_key = ""
+ if cwd:
+ metadata["session_workdir"] = cwd
+ else:
+ metadata.pop("session_workdir", None)
session_target, delivery_target = _validate_definition_update_delivery_target(
session_policy=session_policy,
session_id=session_id,
session_key=session_key,
post_to=post_to,
deliver_key=deliver_key,
+ scope_key=scope_key,
help_command="vibe watch update --help",
)
@@ -5534,6 +6084,7 @@ def cmd_watch_update(args):
"retry_delay_seconds": retry_delay_seconds,
"post_to": post_to,
"deliver_key": deliver_key,
+ "metadata": metadata,
}
current = {
"name": watch.name,
@@ -5553,12 +6104,13 @@ def cmd_watch_update(args):
"retry_delay_seconds": watch.retry_delay_seconds,
"post_to": watch.post_to,
"deliver_key": watch.deliver_key,
+ "metadata": watch.metadata,
}
if changes == current:
raise TaskCliError(
"no watch fields were changed",
code="no_watch_changes",
- hint="Pass at least one field to update, such as --name, --shell, --timeout, --session-id, or --deliver-key.",
+ hint="Pass at least one field to update, such as --name, --shell, --timeout, --session-id, or --scope-id.",
help_command="vibe watch update --help",
details={"watch_id": args.watch_id},
)
@@ -7900,18 +8452,19 @@ def build_parser():
agent_run_parser.add_argument("--agent", help="Avibe Agent name")
agent_run_parser.add_argument("--session-id", help="Existing Agent Session ID to continue")
agent_run_parser.add_argument("--fork-session", help="Existing Agent Session ID to fork into a new Session")
+ agent_run_parser.add_argument("--fork-self", action="store_true", help="Fork the current caller Session from AVIBE_SESSION_ID")
agent_run_parser.add_argument("--create-session", action="store_true", help="Create a new Avibe Session ID before running")
agent_run_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID for each definition run")
- agent_run_parser.add_argument("--deliver-key", help="Scope ID used as delivery target when creating or sending to a target")
+ agent_run_parser.add_argument("--same-scope", action="store_true", help="Place a new or forked Session in the caller/source Session scope")
+ agent_run_parser.add_argument("--scope-id", help="Existing scopes.id that should own the new or forked Session")
+ agent_run_parser.add_argument("--deliver-key", help=argparse.SUPPRESS)
agent_run_parser.add_argument("--model", help="Model override for the new forked Session")
agent_run_parser.add_argument("--reasoning-effort", help="Reasoning effort override for the new forked Session")
agent_run_parser.add_argument(
"--cwd",
help=(
"Working directory for the NEW session. Defaults to the directory the command is "
- "invoked from; sessions created with --deliver-key default to the target scope's "
- "configured workdir instead. Invalid with --session-id (an existing session keeps "
- "its own working directory)."
+ "invoked from. Invalid with --session-id (an existing session keeps its own working directory)."
),
)
agent_run_parser.add_argument("--post-to", choices=("thread", "channel"))
@@ -7945,6 +8498,7 @@ def build_parser():
runs_list_parser.add_argument("--agent", help="Filter by Avibe Agent name")
runs_list_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Filter by backend")
runs_list_parser.add_argument("--session-id", help="Filter by Agent Session ID")
+ runs_list_parser.add_argument("--current-session", action="store_true", help="Filter to the caller Session from AVIBE_SESSION_ID")
runs_list_parser.add_argument("--definition-id", help="Filter by task or watch definition ID")
runs_list_parser.add_argument("--created-after", help="Filter by created_at >= timestamp, or relative value such as 6h or 7d")
runs_list_parser.add_argument("--created-before", help="Filter by created_at <= timestamp, or relative value such as 6h or 7d")
@@ -8433,7 +8987,7 @@ def build_parser():
epilog=_task_add_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe task add --help",
- error_hint="Use --session-id together with exactly one schedule flag and one message input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",
+ error_hint="Use --session-id together with exactly one schedule flag and one message input flag. Use --same-scope or --scope-id when the task creates a new Session.",
)
task_add_parser.add_argument(
"--name",
@@ -8449,7 +9003,10 @@ def build_parser():
)
task_add_parser.add_argument("--create-session", action="store_true", help="Create one reusable Avibe Session ID for this task")
task_add_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this task runs")
+ task_add_parser.add_argument("--same-scope", action="store_true", help="Place a created Session in the caller Session scope")
+ task_add_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")
task_add_parser.add_argument("--agent", help="Avibe Agent name to use when the task runs")
+ task_add_parser.add_argument("--cwd", help="Working directory for Sessions created by this task. Defaults to the caller's current directory.")
delivery_group = task_add_parser.add_mutually_exclusive_group()
delivery_group.add_argument(
"--post-to",
@@ -8458,7 +9015,7 @@ def build_parser():
)
delivery_group.add_argument(
"--deliver-key",
- help="Explicit delivery target key. Use this only when delivery must go to a different target than the continued session.",
+ help=argparse.SUPPRESS,
)
schedule_group = task_add_parser.add_mutually_exclusive_group(required=True)
schedule_group.add_argument("--cron", help="Recurring schedule in 5-field crontab format")
@@ -8491,8 +9048,11 @@ def build_parser():
task_update_parser.add_argument("--session-key", help="Legacy compatibility target; prefer --session-id")
task_update_parser.add_argument("--create-session", action="store_true", help="Replace the task with one reusable newly-created Avibe Session ID")
task_update_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this task runs")
+ task_update_parser.add_argument("--same-scope", action="store_true", help="Place created Sessions in the caller Session scope")
+ task_update_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")
task_update_parser.add_argument("--agent", help="Replace the Avibe Agent used by this task")
task_update_parser.add_argument("--clear-agent", action="store_true", help="Clear the stored Avibe Agent override")
+ task_update_parser.add_argument("--cwd", help="Set working directory for Sessions created by this task")
update_delivery_group = task_update_parser.add_mutually_exclusive_group()
update_delivery_group.add_argument(
"--post-to",
@@ -8501,7 +9061,7 @@ def build_parser():
)
update_delivery_group.add_argument(
"--deliver-key",
- help="Replace the explicit delivery target key",
+ help=argparse.SUPPRESS,
)
task_update_parser.add_argument(
"--reset-delivery",
@@ -8612,7 +9172,7 @@ def build_parser():
epilog=_hook_send_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe hook send --help",
- error_hint="Use --session-id together with exactly one message input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",
+ error_hint="Use 'vibe agent run --async' for new async Agent Runs.",
)
hook_send_parser.add_argument(
"--session-id",
@@ -8631,7 +9191,7 @@ def build_parser():
)
hook_delivery_group.add_argument(
"--deliver-key",
- help="Explicit delivery target key. Use this only when delivery must go to a different target than the continued session.",
+ help=argparse.SUPPRESS,
)
hook_prompt_group = hook_send_parser.add_mutually_exclusive_group(required=True)
hook_prompt_group.add_argument("--message", help="One-shot async user message to queue immediately")
@@ -8675,6 +9235,8 @@ def build_parser():
)
watch_add_parser.add_argument("--create-session", action="store_true", help="Create one reusable Avibe Session ID for this watch")
watch_add_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this watch triggers")
+ watch_add_parser.add_argument("--same-scope", action="store_true", help="Place a created Session in the caller Session scope")
+ watch_add_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")
watch_add_parser.add_argument("--agent", help="Avibe Agent name to use for follow-up messages")
watch_delivery_group = watch_add_parser.add_mutually_exclusive_group()
watch_delivery_group.add_argument(
@@ -8684,7 +9246,7 @@ def build_parser():
)
watch_delivery_group.add_argument(
"--deliver-key",
- help="Explicit delivery target key. Use this only when delivery must go to a different target than the continued session.",
+ help=argparse.SUPPRESS,
)
watch_add_parser.add_argument(
"--prefix",
@@ -8745,7 +9307,7 @@ def build_parser():
epilog="Find watch IDs with: vibe watch list",
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe watch update --help",
- error_hint="Pass at least one field to update, such as --name, --shell, --timeout, --session-id, or --deliver-key.",
+ error_hint="Pass at least one field to update, such as --name, --shell, --timeout, --session-id, or --scope-id.",
)
watch_update_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
watch_update_parser.add_argument("--name", help="Set a human-friendly watch name")
@@ -8760,6 +9322,8 @@ def build_parser():
)
watch_update_parser.add_argument("--create-session", action="store_true", help="Replace the watch with one reusable newly-created Avibe Session ID")
watch_update_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this watch triggers")
+ watch_update_parser.add_argument("--same-scope", action="store_true", help="Place created Sessions in the caller Session scope")
+ watch_update_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")
watch_update_parser.add_argument("--agent", help="Replace the Avibe Agent used for follow-up messages")
watch_update_parser.add_argument("--clear-agent", action="store_true", help="Clear the stored Avibe Agent override")
watch_update_delivery_group = watch_update_parser.add_mutually_exclusive_group()
@@ -8770,7 +9334,7 @@ def build_parser():
)
watch_update_delivery_group.add_argument(
"--deliver-key",
- help="Explicit delivery target key. Use this only when delivery must go to a different target than the continued session.",
+ help=argparse.SUPPRESS,
)
watch_update_delivery_group.add_argument(
"--reset-delivery",