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.

fix: stop deriving session workdir from anchors (#740)

Call Whitea42992fecd92
diff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.py
index eceb6aec9..28ecceb3b 100644
--- a/core/services/agent_run_target.py
+++ b/core/services/agent_run_target.py
@@ -130,13 +130,10 @@ def resolve_agent_run_target(
session_key=session_key,
fallback_anchor=anchor,
workdir=_authoritative_session_workdir(
- conn,
row,
- controller=controller,
platform=platform,
settings_key=settings_key,
session_key=session_key,
- fallback_anchor=anchor,
source="agent_session",
),
source=source,
@@ -173,13 +170,10 @@ def resolve_agent_run_target(
session_key=session_key,
fallback_anchor=anchor,
workdir=_authoritative_session_workdir(
- conn,
existing,
- controller=controller,
platform=platform,
settings_key=settings_key,
session_key=session_key,
- fallback_anchor=anchor,
source="existing_session",
),
source=source,
@@ -543,61 +537,33 @@ def _scope_row(conn, scope_id: str) -> Optional[dict[str, Any]]:
return dict(row) if row is not None else None
-def _scope_workdir(conn, scope_id: Any) -> Optional[str]:
- if not scope_id:
- return None
- value = conn.execute(
- select(scope_settings.c.workdir).where(scope_settings.c.scope_id == str(scope_id))
- ).scalar_one_or_none()
- return _normalize_workdir(value)
-
-
def _authoritative_session_workdir(
- conn,
row: dict[str, Any],
*,
- controller: Any,
platform: str,
settings_key: str,
session_key: str,
- fallback_anchor: str,
source: str,
) -> str:
- """Return ``agent_sessions.workdir`` and repair legacy blanks once.
-
- New sessions must be created with a workdir snapshot. This function exists
- for old rows only: if the stored workdir is missing or is a legacy
- anchor-derived placeholder, choose a migration value and write it back.
- """
-
- session_id = _optional_str(row.get("id"))
- stored = _session_row_workdir(row, fallback_anchor=fallback_anchor)
- if stored:
- return _resolve_workdir(
- stored,
- controller=controller,
- platform=platform,
- settings_key=settings_key,
- session_key=session_key,
- source=source,
- )
+ """Return the existing Session's stored workdir, without fallback."""
- repaired = _resolve_workdir(
- _scope_workdir(conn, row.get("scope_id")),
- controller=controller,
+ session_id = _optional_str(row.get("id")) or "<unknown>"
+ try:
+ stored = _normalize_workdir(row.get("workdir"))
+ except OSError as exc:
+ raise RuntimeError(f"agent session {session_id} has invalid workdir") from exc
+ if not stored:
+ raise RuntimeError(f"agent session {session_id} is missing workdir")
+ ensured = _ensure_workdir(
+ stored,
platform=platform,
settings_key=settings_key,
session_key=session_key,
- source=f"{source}_legacy_repair",
+ source=source,
)
- if session_id:
- conn.execute(
- agent_sessions.update()
- .where(agent_sessions.c.id == session_id)
- .values(workdir=repaired)
- )
- logger.warning("Repaired legacy agent session workdir session_id=%s workdir=%s", session_id, repaired)
- return repaired
+ if not ensured:
+ raise RuntimeError(f"agent session {session_id} workdir is not usable: {stored}")
+ return ensured
def _target_from_session_row(
@@ -669,25 +635,6 @@ def _unpersisted_target(
)
-def _session_row_workdir(row: dict[str, Any], *, fallback_anchor: str) -> Optional[str]:
- workdir = _normalize_workdir(row.get("workdir"))
- if not workdir:
- return None
- native_session_id = _optional_str(row.get("native_session_id"))
- anchor = str(row.get("session_anchor") or fallback_anchor)
- placeholder = _normalize_workdir(_workdir_from_anchor(anchor))
- if not native_session_id and placeholder and workdir == placeholder:
- return None
- return workdir
-
-
-def _workdir_from_anchor(anchor: str) -> Optional[str]:
- if ":" not in anchor:
- return None
- suffix = anchor.rsplit(":", 1)[1]
- return suffix or None
-
-
def _normalize_workdir(value: Any) -> Optional[str]:
text = _optional_str(value)
if not text:
diff --git a/docs/plans/agent-run-scope-semantics.md b/docs/plans/agent-run-scope-semantics.md
index b498a7c13..d15dd6e15 100644
--- a/docs/plans/agent-run-scope-semantics.md
+++ b/docs/plans/agent-run-scope-semantics.md
@@ -60,8 +60,8 @@ to fork into a different scope.
| Operation | Default cwd |
| --- | --- |
| create private/background session | caller shell cwd |
-| create with `--same-scope` | caller shell cwd |
-| create with `--scope-id` | caller shell cwd |
+| create with `--same-scope` | selected scope workdir |
+| create with `--scope-id` | selected scope workdir |
| fork self/session | source session cwd |
| continue existing session | existing session cwd |
| explicit `--cwd` | wins for blank create only |
diff --git a/storage/alembic/versions/20260601_0011_session_anchor_unique.py b/storage/alembic/versions/20260601_0011_session_anchor_unique.py
index d6003640f..c6e302063 100644
--- a/storage/alembic/versions/20260601_0011_session_anchor_unique.py
+++ b/storage/alembic/versions/20260601_0011_session_anchor_unique.py
@@ -5,10 +5,10 @@ backend, keyed by ``(scope_id, session_anchor)`` (see
docs/plans/session-anchor-backend-pin.md):
1. OpenCode used to fold the working directory into ``session_anchor``
- (``base:/path``) to rotate a session per cwd. The cwd now lives only in the
- ``workdir`` column (it is a per-request OpenCode param), so strip the
- ``:<cwd>`` suffix back to the bare base anchor. Only ABSOLUTE-path suffixes
- are stripped, so claude/codex ``base:<subagent>`` anchors are preserved.
+ (``base:/path``) to rotate a session per cwd. Current runtime never trusts
+ that suffix as cwd, so strip the ``:<cwd>`` suffix back to the bare base
+ anchor without deriving ``workdir`` from it. Only ABSOLUTE-path suffixes are
+ stripped, so claude/codex ``base:<subagent>`` anchors are preserved.
2. With anchors normalised, an IM thread that toggled backends (or had a cwd
suffix) can have several rows for one ``(scope_id, session_anchor)``. Reattach
the loser rows' transcripts to the survivor, then keep the most-recently-active
@@ -43,8 +43,8 @@ _UNIQUE_INDEX = "uq_agent_sessions_scope_anchor"
_ABS_CWD_PREFIX = re.compile(r"(/|[A-Za-z]:[\\/]|\\\\)")
-def _split_anchor_cwd(anchor: str) -> tuple[str, str | None]:
- """Split ``base:<abs-cwd>`` into ``(bare_base, cwd)``; passthrough otherwise.
+def _strip_anchor_cwd(anchor: str) -> str:
+ """Strip ``base:<abs-cwd>`` to ``bare_base``; passthrough otherwise.
Splits on the FIRST ``:`` and only strips when the suffix is an absolute path,
so an OpenCode cwd composite (POSIX/Windows/UNC, even double-nested
@@ -53,8 +53,8 @@ def _split_anchor_cwd(anchor: str) -> tuple[str, str | None]:
drive-letter colon that a last-colon split would mangle into ``base:C``."""
base, sep, suffix = anchor.partition(":")
if sep and base and _ABS_CWD_PREFIX.match(suffix):
- return base, suffix
- return anchor, None
+ return base
+ return anchor
def _tables(bind) -> set[str]:
@@ -86,22 +86,22 @@ def upgrade() -> None:
return
# 1. Strip the ``:<cwd>`` suffix OpenCode folded into the anchor back to the
- # bare base, and move the cwd onto the ``workdir`` column. Done row-by-row in
+ # bare base. Do not derive ``workdir`` from that suffix. Done row-by-row in
# Python (not SQL): only an ABSOLUTE-path suffix is a cwd, and recognising
# POSIX + Windows (``C:\``) + UNC absolute paths — and tolerating the Windows
# drive-letter colon — is not expressible in portable SQLite string ops. A
# claude/codex SUBAGENT anchor (``base:reviewer``) is NOT a path and is
# preserved; collapsing it would let the dedup below delete the subagent's
# native binding (lost context). avibe anchors (no ``:``) never match.
- rows = bind.exec_driver_sql("select id, session_anchor, workdir from agent_sessions").fetchall()
- for row_id, anchor, workdir in rows:
+ rows = bind.exec_driver_sql("select id, session_anchor from agent_sessions").fetchall()
+ for row_id, anchor in rows:
if anchor is None:
continue
- bare, cwd = _split_anchor_cwd(str(anchor))
+ bare = _strip_anchor_cwd(str(anchor))
if bare != anchor:
bind.exec_driver_sql(
- "update agent_sessions set session_anchor = ?, workdir = ? where id = ?",
- (bare, cwd if cwd is not None else workdir, row_id),
+ "update agent_sessions set session_anchor = ? where id = ?",
+ (bare, row_id),
)
# 2. Reattach transcripts before dedup deletes the loser rows. messages.session_id
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 899f76862..278d48d56 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -13,6 +13,7 @@ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.exc import IntegrityError
from config import paths
+from config.v2_config import V2Config
from config.v2_sessions import ActivePollInfo, SessionState
from config.v2_settings import _split_scoped_key
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
@@ -20,6 +21,8 @@ from storage.agent_session_rows import (
create_agent_session_row,
decode_session_value,
encode_session_value,
+ normalize_workdir,
+ snapshot_scope_workdir,
)
from storage.models import agent_sessions, metadata, runtime_records, scopes, state_meta
from storage.settings_service import make_scope_id, upsert_scope
@@ -172,9 +175,7 @@ class SQLiteSessionsService:
agent_name=agent_name,
model=model,
reasoning_effort=reasoning_effort,
- # Explicit caller workdir (e.g. the CLI's invocation cwd) wins;
- # None keeps the scope-settings snapshot fallback.
- workdir=workdir,
+ workdir=_new_session_workdir(conn, scope_id, workdir),
metadata={"legacy_scope_key": str(scope_key), **dict(metadata or {})},
now=now,
require_workdir=False,
@@ -695,10 +696,10 @@ class SQLiteSessionsService:
for thread_id, native_session_id in thread_map.items():
thread_key = str(thread_id)
# Normalise OpenCode ``base:/cwd`` composites to the bare
- # anchor (cwd kept on the workdir column) so imported rows
- # match the bare-anchor read path; subagent ``base:<name>``
- # anchors are preserved. Mirrors migration 20260601_0011,
- # which never sees JSON-imported rows (it runs first).
+ # anchor so imported rows match the bare-anchor read path;
+ # subagent ``base:<name>`` anchors are preserved. Workdir is
+ # snapshotted from scope settings, never inferred from the
+ # legacy anchor suffix.
base_anchor = _base_session_anchor(thread_key)
dedup_key = (scope_id, base_anchor)
if dedup_key in seen_anchor_rows:
@@ -728,7 +729,7 @@ class SQLiteSessionsService:
model=None,
reasoning_effort=None,
session_anchor=base_anchor,
- workdir=_workdir_from_anchor(thread_key),
+ workdir=snapshot_scope_workdir(conn, scope_id),
native_session_id=encoded_session_id,
title=None,
status="active",
@@ -745,7 +746,6 @@ class SQLiteSessionsService:
"agent_backend": stmt.excluded.agent_backend,
"agent_variant": stmt.excluded.agent_variant,
"session_anchor": stmt.excluded.session_anchor,
- "workdir": stmt.excluded.workdir,
"native_session_id": stmt.excluded.native_session_id,
"status": stmt.excluded.status,
"metadata_json": stmt.excluded.metadata_json,
@@ -1277,13 +1277,6 @@ def _session_row_key(
return (scope_id, agent_variant, session_anchor, native_session_id)
-def _workdir_from_anchor(anchor: str) -> str | None:
- if ":" not in anchor:
- return None
- suffix = anchor.rsplit(":", 1)[1]
- return suffix or None
-
-
# An ABSOLUTE cwd suffix: POSIX ``/...``, Windows drive ``C:\`` / ``C:/``, or UNC
# ``\\...``. OpenCode's cwd is always absolute (``get_cwd`` -> ``os.path.abspath``),
# so this cleanly separates a cwd composite from a claude/codex subagent name.
@@ -1293,13 +1286,13 @@ _ABS_CWD_PREFIX = re.compile(r"(/|[A-Za-z]:[\\/]|\\\\)")
def _base_session_anchor(anchor: str) -> str:
"""Strip an OpenCode ``base:<abs-cwd>`` suffix back to the bare base anchor.
- The cwd now lives only on the ``workdir`` column; the anchor is the bare thread
- identity. Split on the FIRST ``:`` and drop the suffix iff it is an absolute
- path — POSIX ``/...``, Windows ``C:\\...`` / ``C:/...``, or UNC ``\\\\...``. A
- non-path suffix is a claude/codex subagent name (``base:reviewer``) and is
- preserved. Splitting on the first colon also collapses a double-nested cwd
- (``base:/p:/p``) in one pass and tolerates the drive-letter colon in Windows
- paths (which a last-colon split would mangle into ``base:C``).
+ The anchor is the bare thread identity. Split on the FIRST ``:`` and drop the
+ suffix iff it is an absolute path — POSIX ``/...``, Windows ``C:\\...`` /
+ ``C:/...``, or UNC ``\\\\...``. A non-path suffix is a claude/codex subagent
+ name (``base:reviewer``) and is preserved. Splitting on the first colon also
+ collapses a double-nested cwd (``base:/p:/p``) in one pass and tolerates the
+ drive-letter colon in Windows paths (which a last-colon split would mangle
+ into ``base:C``).
The Python twin of the alembic ``session_anchor`` strip (migration
20260601_0011) for the legacy-JSON import path: ``ensure_sqlite_state`` runs
@@ -1334,3 +1327,18 @@ def _float(value: Any) -> float:
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+
+
+def _runtime_default_workdir() -> str | None:
+ try:
+ config = V2Config.load()
+ return normalize_workdir(config.runtime.default_cwd)
+ except FileNotFoundError:
+ return normalize_workdir(Path.home() / "work")
+ except Exception:
+ logger.debug("Unable to load runtime default workdir", exc_info=True)
+ return None
+
+
+def _new_session_workdir(conn: Connection, scope_id: str | None, explicit_workdir: str | None) -> str | None:
+ return normalize_workdir(explicit_workdir) or snapshot_scope_workdir(conn, scope_id) or _runtime_default_workdir()
diff --git a/tests/test_agent_run_target.py b/tests/test_agent_run_target.py
index 496807b23..958533c95 100644
--- a/tests/test_agent_run_target.py
+++ b/tests/test_agent_run_target.py
@@ -4,13 +4,15 @@ import json
from pathlib import Path
from types import SimpleNamespace
+import pytest
+
from core.services import sessions as sessions_service
from core.services.agent_run_target import resolve_agent_run_target
from modules.im import MessageContext
from storage.agent_session_rows import create_agent_session_row
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import scope_settings
+from storage.models import agent_sessions, scope_settings
from storage.sessions_service import SQLiteSessionsService
from storage.settings_service import upsert_scope
@@ -659,8 +661,10 @@ def test_existing_im_session_workdir_wins_over_scope_change(tmp_path):
assert target.workdir == str(original_workdir)
-def test_reserved_session_placeholder_workdir_falls_back_to_scope(tmp_path):
+def test_existing_session_workdir_does_not_read_anchor_suffix(tmp_path, monkeypatch):
workdir = tmp_path / "channel"
+ deleted_cwd = tmp_path / "deleted-cwd"
+ deleted_cwd.mkdir()
controller = _controller(tmp_path)
with controller.sqlite_engine.begin() as conn:
scope_id = upsert_scope(
@@ -676,8 +680,9 @@ def test_reserved_session_placeholder_workdir_falls_back_to_scope(tmp_path):
session_id = service.reserve_agent_session(
scope_key="slack::channel::C123",
agent_backend="codex",
- session_anchor="slack_scheduled:/tmp/test",
+ session_anchor="slack_scheduled:legacy-suffix",
agent_name="codex",
+ workdir=str(workdir),
)
assert session_id is not None
finally:
@@ -691,22 +696,66 @@ def test_reserved_session_placeholder_workdir_falls_back_to_scope(tmp_path):
"agent_session_id": session_id,
"agent_session_target": {
"id": session_id,
- "session_anchor": "slack_scheduled:/tmp/test",
+ "session_anchor": "slack_scheduled:legacy-suffix",
},
},
)
- target = resolve_agent_run_target(
- ctx,
- controller=controller,
- base_session_id="slack_scheduled:/tmp/test",
- )
+ monkeypatch.chdir(deleted_cwd)
+ deleted_cwd.rmdir()
+
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="slack_scheduled:legacy-suffix")
assert target.agent_session_id == session_id
- assert target.session_anchor == "slack_scheduled:/tmp/test"
+ assert target.session_anchor == "slack_scheduled:legacy-suffix"
assert target.workdir == str(workdir)
+def test_existing_session_missing_workdir_is_rejected(tmp_path, monkeypatch):
+ deleted_cwd = tmp_path / "deleted-cwd"
+ deleted_cwd.mkdir()
+ workdir = tmp_path / "scope"
+ controller = _controller(tmp_path)
+ with controller.sqlite_engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C123",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, scope_id, workdir=str(workdir))
+ session_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_171717.123",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_name="codex",
+ workdir=None,
+ require_workdir=False,
+ )
+ conn.execute(agent_sessions.update().where(agent_sessions.c.id == session_id).values(workdir=None))
+
+ ctx = MessageContext(
+ user_id="U1",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "agent_session_id": session_id,
+ "agent_session_target": {"id": session_id},
+ },
+ )
+
+ monkeypatch.chdir(deleted_cwd)
+ deleted_cwd.rmdir()
+
+ with pytest.raises(RuntimeError, match="missing workdir"):
+ resolve_agent_run_target(ctx, controller=controller, base_session_id="slack_171717.123")
+
+ assert not workdir.exists()
+
+
def test_new_im_session_bind_snapshots_scope_workdir(tmp_path):
original_workdir = tmp_path / "original"
changed_workdir = tmp_path / "changed"
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index 2cef02dea..a8d80f20d 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -1022,7 +1022,7 @@ def test_agent_run_fork_self_uses_caller_session_and_inherits_scope(tmp_path: Pa
assert row["workdir"] == str(tmp_path)
-def test_agent_run_create_same_scope_uses_invocation_workdir(tmp_path: Path, capsys, monkeypatch) -> None:
+def test_agent_run_create_same_scope_snapshots_scope_workdir(tmp_path: Path, capsys, monkeypatch) -> None:
from sqlalchemy import select
from storage.db import create_sqlite_engine
@@ -1063,7 +1063,61 @@ def test_agent_run_create_same_scope_uses_invocation_workdir(tmp_path: Path, cap
finally:
engine.dispose()
assert row["scope_id"] == "avibe::project::proj_fork_cli"
- assert row["workdir"] == str(invoke_dir)
+ assert row["workdir"] == str(tmp_path)
+
+
+def test_agent_run_create_scope_id_snapshots_scope_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"
+ _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",
+ "--scope-id",
+ "avibe::project::proj_fork_cli",
+ "--async",
+ "--no-callback",
+ "--message",
+ "hi",
+ ]
+ )
+ monkeypatch.chdir(invoke_dir)
+
+ 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 == 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(tmp_path)
def test_agent_run_create_scope_id_requires_existing_scope(tmp_path: Path, capsys) -> None:
@@ -1295,17 +1349,19 @@ 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_defaults_to_invocation_cwd(monkeypatch, tmp_path: Path) -> None:
- """Without --cwd, every blank session reservation snapshots the caller cwd.
- An explicit --cwd still wins."""
+def test_resolve_run_cwd_defaults_by_session_target(monkeypatch, tmp_path: Path) -> None:
+ """Without --cwd, private sessions snapshot the caller cwd, while scoped
+ sessions leave cwd unset so creation snapshots the selected scope workdir."""
from types import SimpleNamespace
monkeypatch.chdir(tmp_path)
- args = SimpleNamespace(cwd=None, deliver_key="slack::channel::C123")
+ args = SimpleNamespace(cwd=None)
assert cli._resolve_run_cwd(args, session_policy="create", help_command="x") == str(tmp_path)
+ assert cli._resolve_run_cwd(args, session_policy="create", scoped_session=True, help_command="x") is None
+
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)
+ assert cli._resolve_run_cwd(args, session_policy="create", scoped_session=True, help_command="x") == str(tmp_path)
def test_runs_list_current_session_filters_from_caller_env(tmp_path: Path, capsys) -> None:
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index bd6dd279f..ac173394f 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -629,9 +629,9 @@ def test_task_add_create_per_run_scope_id_records_session_scope_metadata(tmp_pat
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"]["cwd"] is None
assert payload["task"]["metadata"]["session_scope_id"] == "avibe::project::proj-scope-task"
- assert payload["task"]["metadata"]["session_workdir"] == str(invoke_dir)
+ assert "session_workdir" not in payload["task"]["metadata"]
assert payload["task"]["agent_name"] == "project-agent"
@@ -696,10 +696,10 @@ def test_task_add_create_session_scope_id_supports_project_scope(tmp_path: Path,
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 target.workdir == str(tmp_path)
+ assert payload["task"]["cwd"] is None
assert payload["task"]["metadata"]["session_scope_id"] == "avibe::project::proj-once-task"
- assert payload["task"]["metadata"]["session_workdir"] == str(invoke_dir)
+ assert "session_workdir" not in payload["task"]["metadata"]
def test_task_add_create_session_scope_id_uses_unique_definition_anchors(tmp_path: Path, capsys) -> None:
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index a96a85cd7..8b16bd484 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -363,11 +363,11 @@ def test_watch_add_create_per_run_scope_id_records_session_scope_metadata(tmp_pa
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 "session_workdir" not in payload["watch"]["metadata"]
assert payload["watch"]["agent_name"] == "project-agent"
-def test_watch_add_create_session_scope_id_uses_invocation_cwd(tmp_path: Path, capsys) -> None:
+def test_watch_add_create_session_scope_id_snapshots_scope_workdir(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")
@@ -426,9 +426,9 @@ def test_watch_add_create_session_scope_id_uses_invocation_cwd(tmp_path: Path, c
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 target.workdir == str(tmp_path)
assert payload["watch"]["cwd"] == str(invoke_dir)
- assert payload["watch"]["metadata"]["session_workdir"] == str(invoke_dir)
+ assert "session_workdir" not in payload["watch"]["metadata"]
def test_watch_add_defaults_target_to_caller_session(tmp_path: Path, capsys) -> None:
@@ -1140,7 +1140,7 @@ def test_watch_update_allows_cwd_for_already_reserved_create_once_watch(tmp_path
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)
+ assert "session_workdir" not in payload["watch"]["metadata"]
def test_watch_update_rejects_deprecated_prompt_argument(tmp_path: Path) -> None:
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 4cedb3751..50513180c 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import json
from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
import pytest
from sqlalchemy import select
@@ -63,9 +65,16 @@ def test_sessions_store_uses_sqlite_without_rewriting_legacy_json(tmp_path: Path
reloaded = SessionsStore(sessions_path)
try:
# Legacy OpenCode ``base:/cwd`` composite is normalised to the bare anchor
- # on import (cwd -> workdir column), matching the bare-anchor read path; the
- # native id is preserved. (Codex P2: composite anchors were unreadable.)
+ # on import; the native id is preserved, but cwd is not inferred from the
+ # anchor suffix.
assert reloaded.state.session_mappings["slack::C123"]["opencode"]["slack_123.456"] == "session-old"
+ engine = create_sqlite_engine(reloaded.db_path)
+ with engine.connect() as conn:
+ workdir = conn.execute(
+ select(agent_sessions.c.workdir).where(agent_sessions.c.session_anchor == "slack_123.456")
+ ).scalar_one()
+ engine.dispose()
+ assert workdir is None
assert reloaded.state.active_polls["oc-1"]["settings_key"] == "C123"
assert reloaded.state.active_polls["oc-1"]["platform"] == "slack"
assert reloaded.get_active_poll("oc-2") is not None
@@ -351,14 +360,19 @@ def test_bind_agent_session_upgrades_legacy_default_anchor_row(tmp_path: Path, l
def test_sqlite_sessions_service_binds_reserved_agent_session_by_id(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
+ default_workdir = tmp_path / "runtime-default"
service = SQLiteSessionsService(db_path)
try:
- reserved_id = service.reserve_agent_session(
- scope_key="slack::channel::C123",
- agent_backend="opencode",
- session_anchor="slack_private-agent",
- agent_name="opencode",
- )
+ with patch(
+ "storage.sessions_service.V2Config.load",
+ return_value=SimpleNamespace(runtime=SimpleNamespace(default_cwd=str(default_workdir))),
+ ):
+ reserved_id = service.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="opencode",
+ session_anchor="slack_private-agent",
+ agent_name="opencode",
+ )
assert reserved_id is not None
bound_id = service.bind_agent_session_by_id(
@@ -374,7 +388,7 @@ def test_sqlite_sessions_service_binds_reserved_agent_session_by_id(tmp_path: Pa
row = service.get_agent_session_by_id(reserved_id)
assert row is not None
assert row["native_session_id"] == "oc-session-1"
- assert row["workdir"] is None
+ assert row["workdir"] == str(default_workdir)
assert row["agent_id"] == "agent-codex"
assert row["agent_name"] == "codex"
assert row["agent_backend"] == "codex"
@@ -383,6 +397,53 @@ def test_sqlite_sessions_service_binds_reserved_agent_session_by_id(tmp_path: Pa
service.close()
+def test_reserve_agent_session_uses_runtime_default_when_scope_workdir_missing(tmp_path: Path) -> None:
+ from storage.models import scope_settings
+
+ db_path = tmp_path / "vibe.sqlite"
+ default_workdir = tmp_path / "runtime-default"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = upsert_scope(conn, "slack", "channel", "C123", now="2026-07-01T00:00:00Z")
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=None,
+ agent_name="codex",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-07-01T00:00:00Z",
+ updated_at="2026-07-01T00:00:00Z",
+ )
+ )
+
+ with patch(
+ "storage.sessions_service.V2Config.load",
+ return_value=SimpleNamespace(runtime=SimpleNamespace(default_cwd=str(default_workdir))),
+ ):
+ session_id = service.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_171717.123:definition_test",
+ agent_name="codex",
+ )
+
+ assert session_id is not None
+ row = service.get_agent_session_by_id(session_id)
+ assert row is not None
+ assert row["workdir"] == str(default_workdir)
+ finally:
+ service.close()
+
+
def test_bind_agent_session_by_id_does_not_overwrite_existing_workdir(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
service = SQLiteSessionsService(db_path)
@@ -421,18 +482,23 @@ def test_bind_agent_session_by_id_does_not_overwrite_existing_workdir(tmp_path:
def test_bind_agent_session_by_id_does_not_use_anchor_suffix_as_workdir(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
+ default_workdir = tmp_path / "runtime-default"
service = SQLiteSessionsService(db_path)
try:
- reserved_id = service.reserve_agent_session(
- scope_key="slack::channel::C123",
- agent_backend="codex",
- session_anchor="slack_scheduled:/tmp/test",
- agent_name="codex",
- )
+ with patch(
+ "storage.sessions_service.V2Config.load",
+ return_value=SimpleNamespace(runtime=SimpleNamespace(default_cwd=str(default_workdir))),
+ ):
+ reserved_id = service.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_scheduled:/tmp/test",
+ agent_name="codex",
+ )
assert reserved_id is not None
row = service.get_agent_session_by_id(reserved_id)
assert row is not None
- assert row["workdir"] is None
+ assert row["workdir"] == str(default_workdir)
service.bind_agent_session_by_id(
session_id=reserved_id,
@@ -442,7 +508,7 @@ def test_bind_agent_session_by_id_does_not_use_anchor_suffix_as_workdir(tmp_path
row = service.get_agent_session_by_id(reserved_id)
assert row is not None
- assert row["workdir"] is None
+ assert row["workdir"] == str(default_workdir)
finally:
service.close()
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 24e573005..154b81bee 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -1626,7 +1626,7 @@ def _insert_agent_session(
def test_run_migrations_session_anchor_unique_strips_dedups_and_reattaches(tmp_path: Path) -> None:
# Build the pre-0011 schema, seed the exact legacy states 0011 must handle,
# then upgrade to head and assert the three guarantees: OpenCode cwd anchors
- # collapse to the bare base (cwd kept on workdir), claude/codex subagent
+ # collapse to the bare base, claude/codex subagent
# anchors are PRESERVED, duplicate (scope, anchor) rows dedup to the most
# recent, and the loser's transcript is reattached to the survivor first.
db_path = tmp_path / "vibe.sqlite"
@@ -1644,12 +1644,11 @@ def test_run_migrations_session_anchor_unique_strips_dedups_and_reattaches(tmp_p
conn, row_id="ses_sub0000001", scope_id="sc1", anchor="cl-base:reviewer",
workdir="reviewer", backend="claude", native="sub-native", last_active="2026-06-01T08:00:00",
)
- # Windows OpenCode cwd composite (drive-letter colon) -> bare base, cwd
- # re-derived onto workdir. The old last-colon backfill stored a wrong
- # workdir ("\\repo\\x"); the migration corrects it. (Codex P2 #095.)
+ # Windows OpenCode cwd composite (drive-letter colon) -> bare base,
+ # without deriving workdir from the anchor suffix.
_insert_agent_session(
conn, row_id="ses_oswin00001", scope_id="sc1", anchor="win-base:C:\\repo\\x",
- workdir="\\repo\\x", backend="opencode", native="win-native2", last_active="2026-06-01T08:00:00",
+ workdir=None, backend="opencode", native="win-native2", last_active="2026-06-01T08:00:00",
)
# Duplicate group: a bare row + a cwd composite that strips onto it. The
# later last_active row survives; the loser carries a transcript.
@@ -1679,12 +1678,13 @@ def test_run_migrations_session_anchor_unique_strips_dedups_and_reattaches(tmp_p
r[0]: (r[1], r[2])
for r in conn.execute("select id, session_anchor, workdir from agent_sessions")
}
- # OpenCode cwd stripped to bare base; cwd retained on workdir.
+ # OpenCode cwd stripped to bare base; existing workdir retained, but not
+ # derived from the anchor suffix.
assert rows["ses_oc0000001"] == ("oc-base", "/repo/x")
# Subagent anchor preserved (Codex P2: do not collapse base:<subagent>).
assert rows["ses_sub0000001"] == ("cl-base:reviewer", "reviewer")
- # Windows drive-letter cwd stripped to bare base; full cwd on workdir.
- assert rows["ses_oswin00001"] == ("win-base", "C:\\repo\\x")
+ # Windows drive-letter cwd stripped to bare base; workdir remains empty.
+ assert rows["ses_oswin00001"] == ("win-base", None)
# Dedup kept the most-recently-active row; the loser is gone.
assert "ses_win0000001" in rows
assert "ses_lose000001" not in rows
@@ -1768,9 +1768,9 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
assert user_settings == ("admin", None, None)
assert re.fullmatch(r"ses[23456789abcdefghjkmnpqrstuvwxyz]{10}", agent_session[0])
assert agent_session[1] == "slack::channel::C123"
- # OpenCode ``base:/cwd`` composite is normalised to the bare anchor on import
- # (the cwd stays on the ``workdir`` column), matching the migration + the
- # bare-anchor read path. (Codex P2: composite anchors were unreadable.)
+ # Legacy composite anchors are normalised to the bare anchor on import, but
+ # workdir is snapshotted from scope settings rather than inferred from the
+ # anchor suffix.
assert agent_session[2] == "slack_1774074591.762089"
assert agent_session[3] == "/repo"
assert agent_session[4] == "codex-session-1"
@@ -1824,9 +1824,10 @@ def test_ensure_sqlite_state_collapses_multi_backend_anchor_on_import(tmp_path:
with sqlite3.connect(db_path) as conn:
rows = conn.execute("select session_anchor, workdir from agent_sessions").fetchall()
# All three backends collapsed to ONE bare-anchor row — no IntegrityError,
- # no leftover ``slack_T1:/repo`` composite.
+ # no leftover ``slack_T1:/repo`` composite, and no anchor-derived workdir.
assert len(rows) == 1
assert rows[0][0] == "slack_T1"
+ assert rows[0][1] is None
index = conn.execute(
"select name from sqlite_master where type = 'index' and name = 'uq_agent_sessions_scope_anchor'"
).fetchone()
diff --git a/vibe/cli.py b/vibe/cli.py
index f1bcc014e..bd9b82031 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -2058,6 +2058,7 @@ def cmd_task_add(args):
explicit_cwd=getattr(args, "cwd", None),
existing_cwd=None,
session_policy=session_policy,
+ scoped_session=_has_modern_scope_target(args),
help_command="vibe task add --help",
)
agent = _resolve_agent_for_target(
@@ -2435,10 +2436,17 @@ def cmd_task_update(args):
explicit_cwd=explicit_cwd,
existing_cwd=None,
session_policy=session_policy,
+ scoped_session=_has_modern_scope_target(args),
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()
+ cwd = _resolve_definition_session_cwd(
+ explicit_cwd=None,
+ existing_cwd=task.cwd,
+ session_policy=session_policy,
+ scoped_session=_has_modern_scope_target(args) or bool(str(metadata.get("session_scope_id") or "").strip()),
+ help_command="vibe task update --help",
+ )
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)
@@ -3332,12 +3340,18 @@ def _validate_definition_delivery_target(
)
-def _resolve_run_cwd(args, *, session_policy: str, help_command: str) -> Optional[str]:
+def _resolve_run_cwd(
+ args,
+ *,
+ session_policy: str,
+ scoped_session: bool = False,
+ help_command: str,
+) -> Optional[str]:
"""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.
+ Without it, scoped sessions snapshot the scope's default workdir, while
+ private/background sessions follow the CLI invocation's cwd.
Existing and forked sessions keep their own cwd, so ``--cwd`` is an error.
"""
raw = (getattr(args, "cwd", None) or "").strip()
@@ -3356,10 +3370,12 @@ def _resolve_run_cwd(args, *, session_policy: str, help_command: str) -> Optiona
raise TaskCliError(
f"--cwd directory does not exist: {resolved}",
code="cwd_not_found",
- hint="Point --cwd to an existing directory, or omit it to use the invocation directory.",
+ hint="Point --cwd to an existing directory, or omit it to use the session target's default workdir.",
help_command=help_command,
)
return resolved
+ if scoped_session:
+ return None
return os.getcwd()
@@ -3368,6 +3384,7 @@ def _resolve_definition_session_cwd(
explicit_cwd: Optional[str],
existing_cwd: Optional[str],
session_policy: str,
+ scoped_session: bool = False,
help_command: str,
) -> Optional[str]:
raw = (explicit_cwd or "").strip()
@@ -3382,7 +3399,15 @@ def _resolve_definition_session_cwd(
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()
+ if existing_cwd:
+ return existing_cwd
+ if scoped_session:
+ return None
+ return os.getcwd()
+
+
+def _has_modern_scope_target(args) -> bool:
+ return bool((getattr(args, "scope_id", None) or "").strip()) or bool(getattr(args, "same_scope", False))
def _session_creation_metadata_from_caller(caller_context) -> dict:
@@ -3655,7 +3680,6 @@ def cmd_agent_run(args):
)
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():
@@ -3664,6 +3688,12 @@ def cmd_agent_run(args):
# 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
+ run_cwd = _resolve_run_cwd(
+ args,
+ session_policy=session_policy,
+ scoped_session=bool(scope_key),
+ help_command="vibe agent run --help",
+ )
agent = _agent_store().require_enabled(agent_name) if agent_name else None
fork_result = None
session_metadata = _session_creation_metadata_from_caller(caller_context)
@@ -5857,11 +5887,22 @@ def cmd_watch_add(args):
)
agent_name = agent.name if agent else None
cwd = _resolve_watch_cwd(args.cwd, help_command="vibe watch add --help", default_to_invocation=True)
+ session_workdir = (
+ _resolve_definition_session_cwd(
+ explicit_cwd=getattr(args, "cwd", None),
+ existing_cwd=None,
+ session_policy=session_policy,
+ scoped_session=_has_modern_scope_target(args),
+ help_command="vibe watch add --help",
+ )
+ if session_policy != "existing"
+ else None
+ )
if session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
deliver_key=scope_key or "",
- workdir=cwd,
+ workdir=session_workdir,
help_command="vibe watch add --help",
)
session_target, delivery_target = _validate_definition_delivery_target(
@@ -5910,7 +5951,7 @@ def cmd_watch_add(args):
deliver_key=args.deliver_key,
agent_name=agent_name,
session_policy=session_policy,
- metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),
+ metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=session_workdir),
)
runtime_store = _watch_runtime_store()
watch, runtime_entry = _wait_for_watch_startup(store, runtime_store, watch.id)
@@ -6150,6 +6191,22 @@ def cmd_watch_update(args):
next_schedule_type="watch",
help_command="vibe watch update --help",
)
+ creates_future_session = session_policy == "create_per_run" or (
+ session_policy == "create_once" and (bool(getattr(args, "create_session", False)) or not session_id)
+ )
+ session_workdir = (
+ _resolve_definition_session_cwd(
+ explicit_cwd=getattr(args, "cwd", None),
+ existing_cwd=None
+ if getattr(args, "clear_cwd", False)
+ else (str(metadata.get("session_workdir") or "").strip() or None),
+ session_policy=session_policy,
+ scoped_session=_has_modern_scope_target(args) or bool(str(metadata.get("session_scope_id") or "").strip()),
+ help_command="vibe watch update --help",
+ )
+ if creates_future_session
+ else None
+ )
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(
@@ -6180,12 +6237,12 @@ def cmd_watch_update(args):
session_id = _reserve_definition_session(
agent_name=agent_name,
deliver_key=scope_key,
- workdir=cwd,
+ workdir=session_workdir,
help_command="vibe watch update --help",
)
session_key = ""
- if cwd:
- metadata["session_workdir"] = cwd
+ if session_workdir:
+ metadata["session_workdir"] = session_workdir
else:
metadata.pop("session_workdir", None)
session_target, delivery_target = _validate_definition_update_delivery_target(
@@ -8595,8 +8652,9 @@ def build_parser():
agent_run_parser.add_argument(
"--cwd",
help=(
- "Working directory for the NEW session. Defaults to the directory the command is "
- "invoked from. Invalid with --session-id (an existing session keeps its own working directory)."
+ "Working directory for the NEW session. Private sessions default to the invocation "
+ "directory; scoped sessions default to the scope workdir. Invalid with --session-id "
+ "(an existing session keeps its own working directory)."
),
)
agent_run_parser.add_argument("--post-to", choices=("thread", "channel"), help=argparse.SUPPRESS)