Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): give a pane the user's own CLI setup, not a stripped copy
Ruben Lütkeff6ee578ff2a
diff --git a/docs/superpowers/specs/2026-07-26-agent-account-switching-design.md b/docs/superpowers/specs/2026-07-26-agent-account-switching-design.mdindex efc39b67d3..c13d9533b9 100644--- a/docs/superpowers/specs/2026-07-26-agent-account-switching-design.md+++ b/docs/superpowers/specs/2026-07-26-agent-account-switching-design.md@@ -179,3 +179,68 @@ runs a shell string).- `tests/unit/test_agent_accounts_routes.py` — route contract + danger metadata.- Frontend: the accounts panel renders, switches, and shows an unsigned accounthonestly.++---++## 8. Follow-up 2026-07-27 — the redirect cost the user their whole CLI++**Reported symptom.** An Agentic-IDE pane "is not a real Claude Code session":+in a normal terminal the maintainer sees 93 skills, thirteen plugins and their+global instructions; in a pane, only the CLI's built-in skills and the project's+own `.claude/`. Same machine, same binary, same folder.++**Cause.** §2's mechanism is sound about the login and wrong about everything+else in that directory. `CLAUDE_CONFIG_DIR` / `CODEX_HOME` do not move a+credential — they move the CLI's **entire user level**: `skills/`, `agents/`,+`commands/`, `hooks/`, `output-styles/`, `plugins/` (marketplaces = connectors),+the user-level `CLAUDE.md` / `AGENTS.md`, and `settings.json` /+`config.toml`. An account directory holds none of that, so every pane on an+added subscription ran a quieter, emptier version of the CLI the user installed.+`inherit_default_mode` had already patched the narrowest instance of this (the+operating mode) without recognising the class.++The Agentic IDE is the ONLY spawn path that passes `env=` to the PTY manager,+which is exactly why the same CLI behaves correctly in every other terminal+Jarvis opens.++**Resolution — `jarvis/agent_config_parity.py`.** Before every pane spawn, a+redirected config dir is given the user's own setup:++- **Directories are linked** — symlink, or a Windows **junction** where symlink+ creation needs a privilege the app does not have (measured: `WinError 1314` on+ the maintainer's non-elevated install), or a copy where neither works. A link+ means a skill installed today is in every account tomorrow.+- **Files are mirrored, then merged** — a file the account does not have is+ copied and tracked by digest, so a later change to the user's file follows+ through. A file the account has written to itself (a pane that changed its+ theme) is never overwritten: the keys it is **missing** are filled in+ recursively instead. Without that last step the fix was half a fix — the+ plugin trees arrived while `enabledPlugins` stayed absent, so nothing loaded.+- **`plugins/` is shared whole or not at all.** Which plugins are active lives+ in state files beside the marketplaces they name; the account's half-written+ copy is moved to `plugins.jarvis-superseded` and replaced by the user's.+- **Identity is untouched by construction** — an explicit allowlist, so+ `.credentials.json`, `auth.json`, `.claude.json`, `projects/`, `sessions/` and+ `history.jsonl` are never shared. Claude Code's user-scope MCP servers are+ merged out of `.claude.json` one key at a time, because that document holds+ the login too.+- **Never raises.** Every failure degrades to one unshared entry plus a log+ line, and the report names it — a pane must open either way.++**Second defect found on the way.** `jarvis/workspace/trust.py` seeded folder+trust only into the machine's default config, so a pane on an added account met+the "do you trust this directory?" dialog — which voice and the prompt bar+cannot answer. `ensure_trusted` now takes `config_dirs`, and the registry+pre-trusts the directory each pane will actually run from (once per folder and+account).++**Scope.** Agentic-IDE panes only. Mission workers keep their deliberately+isolated, hook-free environment (§6), and a pane on the built-in login still+spawns with a plain inherited environment — byte for byte what it always was.++**Tests.** `tests/unit/test_agent_config_parity.py` (the setup arrives and keeps+arriving; identity is never shared; an account's own value survives while its+missing keys are filled; symlink host, junction host, copy-only host, and a host+that can do none of it), plus `tests/unit/agentic_ide/test_account_spawn.py`+(the pane spawn provisions and pre-trusts) and `tests/unit/workspace/+test_trust.py` (per-account trust, de-duplicated).diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.pyindex a66cc408a6..17728e854d 100644--- a/jarvis/agent_accounts.py+++ b/jarvis/agent_accounts.py@@ -190,6 +190,17 @@ def _native_dir(platform: Platform) -> Path:return Path(os.path.expanduser(_NATIVE_DIR[platform]))+def native_dir(platform: Platform) -> Path:+ """Public name for the directory the CLI reads when nothing is redirected.++ A thin wrapper on purpose: it delegates at CALL time, so a test that+ redirects the private implementation still governs every caller — including+ :mod:`jarvis.agent_config_parity`, which needs this to know whose setup a+ redirected account dir has to carry.+ """+ return _native_dir(platform)++def builtin_id(platform: Platform) -> str:"""The stable id of a platform's synthetic default account."""return f"{platform}:default"@@ -662,9 +673,28 @@ def _write_settings(path: Path, text: str) -> bool:return True+def mode_file_name(platform: Platform) -> str | None:+ """Which file inside a config dir carries that CLI's default mode.++ Read by callers that share the WHOLE file (see+ :mod:`jarvis.agent_config_parity`): once the user's own settings file is+ mirrored across, the narrow per-key mirror below has nothing left to do, and+ running it anyway would only risk disagreeing with the file it just copied.+ """+ spec = _MODE_FILES.get(platform)+ return None if spec is None else spec.name++def inherit_default_mode(platform: Platform, account_id: str | None) -> bool:"""Carry the user's default operating mode into a redirected config home.+ Superseded for the common case by :func:`jarvis.agent_config_parity.+ ensure_parity`, which shares the entire settings file and therefore carries+ the mode with it. This stays for the case that one cannot serve: an account+ whose settings file is its OWN (hand-edited, or written by the CLI inside a+ running pane) is never overwritten wholesale, and the mode keys are still+ worth carrying into it one at a time.+**The gap this closes.** Pointing ``CLAUDE_CONFIG_DIR`` / ``CODEX_HOME`` atan account's own directory moves the CLI's whole user-level configuration,not only its login — and the default operating mode lives there. So a pane on@@ -973,6 +1003,8 @@ __all__ = ["env_overrides","inherit_default_mode","list_accounts",+ "mode_file_name",+ "native_dir","rename_account","resolve","set_active",diff --git a/jarvis/agent_config_parity.py b/jarvis/agent_config_parity.pynew file mode 100644index 0000000000..1c7a85ef51--- /dev/null+++ b/jarvis/agent_config_parity.py@@ -0,0 +1,694 @@+"""Give a redirected coding-CLI config dir the user's OWN setup.++An Agentic-IDE pane has to be the same session the user gets by typing+``claude`` or ``codex`` in an ordinary terminal: the same skills, subagents,+slash commands, plugins and connectors, hooks, output styles and user-level+memory file. A pane on the built-in login gets that for free — it spawns with a+plain inherited environment, byte for byte what a terminal would have.++A pane on an ADDED subscription does not. Switching accounts works by pointing+the CLI's own config-dir override (``CLAUDE_CONFIG_DIR`` / ``CODEX_HOME``) at a+directory of that account's own (:mod:`jarvis.agent_accounts`) — and that+directory carries the CLI's whole USER LEVEL, not just its login. So the+redirect that buys a second subscription silently costs the user's entire setup.+Measured on a real install (2026-07-27): a pane on an added account saw the+CLI's built-in skills plus the project's ``.claude/`` and nothing else, while+the same CLI in a normal terminal saw 93 user skills, thirteen plugins and the+user's global instructions. That is not a smaller session, it is a different+product — and it is the gap this module closes.++**An explicit allowlist, never a denylist.** Only what a CLI reads as+user-level CONFIGURATION or EXTENSIONS is shared (:data:`USER_SETUP`).+Everything that identifies the account or belongs to its conversations —+``.credentials.json``, ``auth.json``, ``.claude.json``, ``projects/``,+``sessions/``, ``history.jsonl`` — is untouched by construction, because it is+not on the list. That direction matters: sharing a credential file is exactly+the failure the account feature exists to prevent (see+:mod:`jarvis.claude_credentials` — a copied OAuth token starts dying the moment+it is made), whereas a config entry nobody listed yet merely stays missing until+someone adds it.++**Directories are LINKED, single files are MIRRORED.** The difference is not+cosmetic:++* A directory link (symlink, or a junction on Windows where symlinks need a+ privilege) means the pane reads the user's real ``skills/`` folder. A skill+ installed today shows up in every account tomorrow, nothing is duplicated on+ disk, and a plugin the CLI installs from inside a pane lands where the user's+ other terminals will see it. Where no link can be made at all, the tree is+ copied instead — except for entries marked :attr:`Shared.copy_fallback`+ ``False``, which are large and mutable enough (``plugins/``) that a copy would+ be a lie dressed as a feature; those are reported as skipped.+* A single file is COPIED, and deliberately not linked: several components write+ into a config dir with an atomic ``os.replace``, which silently replaces a+ link with a private file. A copy cannot be broken that way. The copy is+ guarded by a digest recorded in :data:`STATE_FILE`, so a later change to the+ user's global file follows through, while a value written for that account —+ by hand, or by the CLI itself inside a pane — is never overwritten.++**Idempotent and self-healing.** It runs before every pane spawn: a few stat+calls when everything is already in place, a re-link when something replaced a+share with a copy, and a repair when a link went dangling because the user+deleted the entry it pointed at.++**Never raises.** A pane must open even when a link cannot be created or a file+cannot be read; every failure degrades to that entry staying unshared, with a+log line naming it. Callers get a :class:`ParityReport` and can say out loud+what did not make it across.++Cross-platform by construction: ``pathlib`` throughout, POSIX symlinks,+Windows junctions where symlink creation is refused, and a copy as the last+resort on any host that allows neither. Nothing here is specific to one OS's+filesystem layout — the entry names come from the CLIs, not from the platform.+"""++from __future__ import annotations++import json+import os+import shutil+import sys+from dataclasses import dataclass, field+from hashlib import sha256+from pathlib import Path+from typing import Any, Literal++from loguru import logger++from jarvis.agent_accounts import Platform, native_dir, resolve++#: Bumped when the state file's shape changes incompatibly. An unknown version+#: reads as "nothing has been mirrored yet", which costs one refresh of the+#: mirrored files and never a wrong "this was the user's own value" verdict.+STATE_VERSION = 1++#: Where this module records what it last copied across. Lives inside the+#: account's own directory (next to :data:`jarvis.agent_accounts._MIRROR_FILE`)+#: so forgetting the account forgets its bookkeeping too. Losing the file is+#: harmless: every mirrored file then counts as the account's own.+STATE_FILE = "jarvis-shared-setup.json"++#: Appended to an account-local folder that the user's own tree replaces. Kept+#: beside it rather than deleted — see :func:`_supersede`.+SUPERSEDED_SUFFIX = ".jarvis-superseded"+++@dataclass(frozen=True, slots=True)+class Shared:+ """One entry of a CLI's user level that a redirected dir must also have."""++ #: Entry name inside the config directory, exactly as the CLI reads it.+ name: str+ kind: Literal["dir", "file"]+ #: How a FILE is structured, which decides what happens when the account+ #: already has one of its own: a document can be filled key by key, plain+ #: text can only be taken whole or left alone. Ignored for directories.+ fmt: Literal["json", "toml", "text"] = "text"+ #: May this entry be COPIED on a host where no link can be created? False+ #: for trees that are large or that the CLI rewrites constantly — a copy of+ #: those goes stale invisibly, and "missing, and said so" beats that.+ copy_fallback: bool = True+ #: Does this tree only work as a WHOLE? Set for a directory whose files and+ #: subfolders reference each other, so half of it shared and half of it the+ #: account's own is not a partial success but a broken state. Such a tree+ #: supersedes a copy the CLI made for the account (kept beside it under+ #: :data:`SUPERSEDED_SUFFIX`) instead of being merged into it.+ whole: bool = False+++@dataclass(frozen=True, slots=True)+class MergedKey:+ """One top-level key of a JSON document that must carry the user's value.++ For documents that mix user configuration with account IDENTITY. Claude+ Code's ``.claude.json`` is the case that forces this: user-scope MCP servers+ (the "connectors" a pane is expected to have) live in it beside+ ``oauthAccount`` and ``userID``, so the document cannot be shared as a whole+ — one key can.+ """++ name: str+ key: str+++#: What "the user's setup" IS, per CLI. Order is presentation only.+#:+#: Deliberately absent, and it must stay that way: credentials+#: (``.credentials.json``, ``auth.json``), the per-account conversation record+#: (``projects/``, ``sessions/``, ``history.jsonl``, ``shell-snapshots/``), and+#: caches. Those are what makes two accounts two accounts.+USER_SETUP: dict[Platform, tuple[Shared, ...]] = {+ "claude": (+ # User-level memory: the instructions every session of the user's starts+ # with. A pane without it answers differently from their terminal.+ Shared("CLAUDE.md", "file"),+ # User settings: model, output style, permissions, hooks, statusLine,+ # env, enabled plugins and known marketplaces. This is also what carries+ # the default operating mode, which is why this module supersedes the+ # narrow mode mirror in jarvis.agent_accounts.inherit_default_mode.+ Shared("settings.json", "file", fmt="json"),+ Shared("settings.local.json", "file", fmt="json"),+ Shared("skills", "dir"),+ Shared("agents", "dir"),+ Shared("commands", "dir"),+ Shared("hooks", "dir"),+ Shared("output-styles", "dir"),+ # Installed plugins and their marketplaces — the connectors a pane is+ # expected to have. Never copied: the tree holds cloned repositories and+ # the CLI rewrites its state files, so a copy would be a stale snapshot+ # of somebody's plugin set rather than their plugin set. And never half+ # shared: which plugins are ACTIVE lives in state files beside the+ # marketplaces they name, so the user's marketplaces next to the+ # account's own state list nothing the CLI can load.+ Shared("plugins", "dir", copy_fallback=False, whole=True),+ ),+ "codex": (+ Shared("AGENTS.md", "file"),+ # Codex keeps its whole configuration in one file — model, approval+ # policy, sandbox, and [mcp_servers] — and its login in a separate+ # auth.json, so the config file can be shared as a whole.+ Shared("config.toml", "file", fmt="toml"),+ Shared("hooks.json", "file", fmt="json"),+ Shared("prompts", "dir"),+ Shared("skills", "dir"),+ ),+}++#: Keys merged out of a document that also holds identity. See :class:`MergedKey`.+MERGED_KEYS: dict[Platform, tuple[MergedKey, ...]] = {+ "claude": (MergedKey(".claude.json", "mcpServers"),),+ # Codex's mcp_servers live in config.toml, which is shared whole above.+ "codex": (),+}+++@dataclass(frozen=True, slots=True)+class ParityReport:+ """What a redirected config dir now shares with the user's own.++ ``shared`` maps an entry name to HOW it is shared — ``linked`` / ``junction``+ (the pane reads the user's real folder), ``copied``, ``mirrored`` (a file+ copy that tracks the user's), ``merged`` (one key of a document), or+ ``current`` (already in place, nothing to do). ``skipped`` carries a reason+ per entry that could not come across, so a caller can report it instead of+ quietly delivering less.+ """++ shared: dict[str, str] = field(default_factory=dict)+ skipped: tuple[tuple[str, str], ...] = ()+ #: False when nothing was redirected in the first place (the built-in login),+ #: which is the case where a pane already spawns exactly like a terminal.+ redirected: bool = False++ @property+ def names(self) -> tuple[str, ...]:+ return tuple(self.shared)+++# ----------------------------------------------------------------- state file+++def _state_path(config_dir: Path) -> Path:+ return config_dir / STATE_FILE+++def _read_state(config_dir: Path) -> dict[str, str]:+ """The digests of the files this module last copied across.++ Every failure mode — missing, truncated, hand-edited, written by a newer+ build — answers the same empty mapping, which costs one refresh and never a+ wrong verdict about whose value a file holds.+ """+ try:+ raw = _state_path(config_dir).read_text(encoding="utf-8-sig")+ except OSError:+ return {}+ try:+ data = json.loads(raw or "{}")+ except ValueError:+ return {}+ if not isinstance(data, dict) or data.get("version") != STATE_VERSION:+ return {}+ digests = data.get("digests")+ if not isinstance(digests, dict):+ return {}+ return {str(k): str(v) for k, v in digests.items()}+++def _write_state(config_dir: Path, digests: dict[str, str]) -> None:+ payload = json.dumps(+ {"version": STATE_VERSION, "digests": digests}, indent=2, ensure_ascii=False+ )+ _atomic_write(_state_path(config_dir), payload)+++def _atomic_write(path: Path, text: str) -> bool:+ """Replace ``path`` in one step — a half-written config must never be read."""+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")+ tmp.write_text(text, encoding="utf-8")+ os.replace(tmp, path)+ except OSError as exc:+ logger.warning("Agent setup: {} could not be written: {}", path, exc)+ return False+ return True+++def _digest(path: Path) -> str | None:+ """Content digest of one file, or ``None`` when it cannot be read."""+ try:+ return sha256(path.read_bytes()).hexdigest()+ except OSError:+ return None+++# ---------------------------------------------------------------- link layer+++def _same_path(left: Path, right: Path) -> bool:+ return os.path.normcase(str(left)) == os.path.normcase(str(right))+++def _resolves_to(target: Path, source: Path) -> bool:+ """Is ``target`` already a link that lands on ``source``?++ Resolved rather than read: this must answer True for a POSIX symlink AND for+ a Windows junction, and ``os.path.islink`` is documented to answer False for+ junctions. ``Path.resolve`` follows both.+ """+ try:+ return _same_path(target.resolve(strict=True), source.resolve(strict=True))+ except OSError:+ return False+++def _dangling(path: Path) -> bool:+ """A link whose target is gone — the user deleted the entry we pointed at."""+ return os.path.lexists(path) and not path.exists()+++def _remove(path: Path) -> bool:+ """Drop a link (never its target). Directory links unlink on POSIX, rmdir on+ Windows, so both are tried before giving up."""+ for attempt in (os.unlink, os.rmdir):+ try:+ attempt(path)+ return True+ except OSError:+ continue+ logger.debug("Agent setup: {} could not be removed", path)+ return False+++def _link(source: Path, target: Path) -> str | None:+ """Point ``target`` at ``source``. Returns how, or ``None`` if impossible.++ A symlink first, because it is the one mechanism both filesystems and both+ CLIs treat identically. On Windows creating one needs Developer Mode or an+ elevated process, so a refusal falls back to a junction — a reparse point+ that needs no privilege, is transparent to every file API, and only works+ for directories, which is all this path is used for.+ """+ is_dir = source.is_dir()+ try:+ os.symlink(source, target, target_is_directory=is_dir)+ return "linked"+ except (OSError, NotImplementedError, AttributeError) as exc:+ logger.debug("Agent setup: symlink {} -> {} refused ({})", target, source, exc)+ if is_dir and sys.platform == "win32":+ try:+ import _winapi # noqa: PLC0415 - CPython-internal, Windows-only++ _winapi.CreateJunction(str(source), str(target)) # type: ignore[attr-defined]+ return "junction"+ except (OSError, AttributeError, ImportError) as exc:+ logger.debug("Agent setup: junction {} -> {} failed ({})", target, source, exc)+ return None+++def _copy(source: Path, target: Path) -> str | None:+ """Last resort where no link can be made. Returns ``"copied"`` or ``None``."""+ try:+ if source.is_dir():+ # A user's skills folder can itself contain symlinks; following them+ # keeps the copy usable, and a dangling one is skipped rather than+ # failing the whole tree.+ shutil.copytree(+ source, target, symlinks=False, dirs_exist_ok=True, ignore_dangling_symlinks=True+ )+ else:+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source, target)+ except (OSError, shutil.Error) as exc:+ logger.debug("Agent setup: copying {} to {} failed ({})", source, target, exc)+ return None+ return "copied"+++def _supersede(target: Path) -> Path | None:+ """Move an account-local copy aside so the user's own tree can take its place.++ Kept rather than deleted, and only ever done when the backup name is free —+ so this can run before every spawn without stacking up folders, and a+ surprised user can always look at what was replaced. Returns where it went,+ or ``None`` when it could not be moved (the caller then merges instead).+ """+ backup = target.with_name(target.name + SUPERSEDED_SUFFIX)+ if os.path.lexists(backup):+ return None+ try:+ os.rename(target, backup)+ except OSError as exc:+ logger.debug("Agent setup: {} could not be moved aside ({})", target, exc)+ return None+ return backup+++def _share_dir(+ source: Path, target: Path, *, copy_fallback: bool, whole: bool+) -> tuple[str | None, str]:+ """Make ``target`` carry ``source``'s directory. Returns ``(how, reason)``.++ Four states, and the third is the one that keeps this safe:++ 1. Nothing there — link the whole directory (one reparse point, live).+ 2. Already our link — nothing to do.+ 3. A REAL directory the CLI created for this account. Its own entries stay,+ and only the children the account is missing are linked in — so an+ account-local skill or subagent is never discarded. A tree marked+ :attr:`Shared.whole` takes the other route: it is moved aside and+ replaced by the user's, because half of that tree is worse than none of+ it (see ``plugins`` in :data:`USER_SETUP`).+ 4. A link somewhere else entirely — left alone and reported, because it is+ not this module's to redirect.+ """+ if _dangling(target):+ _remove(target)+ if not os.path.lexists(target):+ how = _link(source, target)+ if how is None and copy_fallback:+ how = _copy(source, target)+ if how is None:+ return None, "this host allows neither a link nor a usable copy"+ return how, ""+ if _resolves_to(target, source):+ return "current", ""+ if not target.is_dir():+ return None, "the account has a file of its own by that name"+ if whole:+ moved = _supersede(target)+ if moved is not None:+ how = _link(source, target)+ if how is None and copy_fallback:+ how = _copy(source, target)+ if how is not None:+ logger.info(+ "Agent setup: {} now comes from your own setup — what was there is kept at {}",+ target.name,+ moved.name,+ )+ return how, ""+ # Nothing could take its place, so put back exactly what was there.+ try:+ os.rename(moved, target)+ except OSError as exc: # pragma: no cover - defensive+ logger.warning(+ "Agent setup: {} was moved to {} and could not be put back: {}",+ target,+ moved,+ exc,+ )+ return None, "this host allows neither a link nor a usable copy"+ return None, "this host cannot share that folder as a whole"+ linked = 0+ for child in _children(source):+ spot = target / child.name+ if _dangling(spot):+ _remove(spot)+ if os.path.lexists(spot):+ continue+ how = _link(child, spot)+ if how is None and copy_fallback:+ how = _copy(child, spot)+ if how is not None:+ linked += 1+ if linked:+ return "linked", ""+ return "current", ""+++def _children(source: Path) -> list[Path]:+ try:+ return sorted(source.iterdir())+ except OSError as exc:+ logger.debug("Agent setup: {} could not be listed ({})", source, exc)+ return []+++# ---------------------------------------------------------------- file layer+++def _share_file(+ source: Path,+ target: Path,+ *,+ key: str,+ fmt: str,+ state: dict[str, str],+) -> tuple[str | None, str]:+ """Give the account ``source``'s content without overwriting its own choices.++ Three outcomes, and the third is the one that matters most in practice:++ * the account has no such file, or still has exactly what was last copied+ across — then it is a mirror of the user's file and simply follows it+ (``mirrored`` / ``current``);+ * the file has its own content AND a structure to merge into — then the keys+ the account is MISSING are filled in from the user's, recursively, and+ every key it already has is left exactly as it is (``merged``). This is the+ normal state of a config a pane has ever written to: a pane that changed+ its theme must keep that theme, and must still get the user's plugins,+ permissions and status line;+ * the file has its own content and no structure (a plain-text memory file) —+ then there is nothing to merge and it stays the account's own.++ A merged file is deliberately NOT recorded in ``state``: it is nobody's copy+ any more, so the next run fills what is missing again rather than replacing+ the hybrid with the user's file wholesale.+ """+ source_digest = _digest(source)+ if source_digest is None:+ return None, "the user's own file could not be read"+ target_digest = _digest(target) if target.exists() else None+ if target_digest == source_digest:+ state[key] = source_digest+ return "current", ""+ if target_digest is None or target_digest == state.get(key):+ if _copy(source, target) is None:+ return None, "the copy could not be written"+ state[key] = source_digest+ return "mirrored", ""+ if fmt == "text":+ return None, "this account has its own version of that file"+ filled, why = _fill_missing(source, target, fmt)+ if filled is None:+ return None, why+ state.pop(key, None)+ return filled, ""+++def _read_document(path: Path, fmt: str) -> dict[str, Any] | None:+ """A config document as plain Python values, or ``None`` if unusable."""+ try:+ raw = path.read_text(encoding="utf-8-sig")+ except OSError:+ return None+ try:+ if fmt == "toml":+ import tomllib # noqa: PLC0415 - stdlib, only for TOML platforms++ data: Any = tomllib.loads(raw)+ else:+ data = json.loads(raw or "{}")+ except (ValueError, UnicodeDecodeError):+ return None+ return data if isinstance(data, dict) else None+++def _fill(source: Any, target: Any) -> bool:+ """Add the keys ``target`` lacks, recursively. Returns whether it changed.++ Only ADDS. A value the account already holds is never replaced — not even a+ nested one — and a list is treated as one value rather than merged item by+ item, because a permission list the account narrowed on purpose must not+ silently regain the entries it dropped.+ """+ changed = False+ for name, value in source.items():+ if name not in target:+ target[name] = value+ changed = True+ elif isinstance(value, dict) and isinstance(target[name], dict):+ changed = _fill(value, target[name]) or changed+ return changed+++def _fill_missing(source: Path, target: Path, fmt: str) -> tuple[str | None, str]:+ """Fill the keys the account's own file is missing from the user's."""+ native = _read_document(source, fmt)+ if native is None:+ return None, "the user's own file could not be read"+ if fmt == "toml":+ import tomlkit # noqa: PLC0415 - only needed to WRITE a TOML document++ try:+ doc: Any = tomlkit.parse(target.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError, UnicodeDecodeError):+ return None, "this account's own file could not be read"+ if not _fill(native, doc):+ return "current", ""+ rendered = tomlkit.dumps(doc)+ else:+ own = _read_document(target, fmt)+ if own is None:+ return None, "this account's own file could not be read"+ if not _fill(native, own):+ return "current", ""+ rendered = json.dumps(own, indent=2, ensure_ascii=False)+ if not _atomic_write(target, rendered):+ return None, "the merged file could not be written"+ return "merged", ""+++def _merge_key(+ source: Path, target: Path, key: str, *, state_key: str, state: dict[str, str]+) -> tuple[str | None, str]:+ """Carry ONE key across, leaving every other key of both documents alone."""+ native = _read_document(source, "json")+ if not native or key not in native:+ return None, "" # nothing on the user's side to carry — not a failure+ wanted = native[key]+ try:+ encoded = json.dumps(wanted, sort_keys=True, ensure_ascii=False)+ except (TypeError, ValueError):+ return None, "that setting cannot be represented"+ digest = sha256(encoded.encode("utf-8")).hexdigest()+ doc = _read_document(target, "json")+ if doc is None:+ doc = {}+ if key in doc:+ try:+ current = json.dumps(doc[key], sort_keys=True, ensure_ascii=False)+ except (TypeError, ValueError):+ current = ""+ if current == encoded:+ state[state_key] = digest+ return "current", ""+ if sha256(current.encode("utf-8")).hexdigest() != state.get(state_key):+ return None, "this account has its own version of that setting"+ doc[key] = wanted+ if not _atomic_write(target, json.dumps(doc, indent=2, ensure_ascii=False)):+ return None, "the document could not be written"+ state[state_key] = digest+ return "merged", ""+++# --------------------------------------------------------------------- public+++def ensure_parity(platform: Platform, account_id: str | None) -> ParityReport:+ """Make ``account_id``'s config dir carry the user's own setup for ``platform``.++ A no-op — and an empty report — for the built-in login, for an unknown+ account, and for a host where the account's directory IS the native one.+ Nothing was redirected in those cases, so nothing was lost.++ Safe to call before every spawn: idempotent, cheap when everything is in+ place, and never raising.+ """+ account = resolve(account_id)+ if account is None or account.platform != platform or account.builtin:+ return ParityReport()+ native = native_dir(platform)+ if _same_path(native, account.config_dir):+ return ParityReport()+ if not native.is_dir():+ # The user has no setup of their own yet (a fresh machine): there is+ # nothing to share, and the account's own defaults are the whole truth.+ return ParityReport(redirected=True)+ try:+ account.config_dir.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ logger.warning("Agent setup: {} is not usable: {}", account.config_dir, exc)+ return ParityReport(redirected=True, skipped=((str(account.config_dir), str(exc)),))++ state = _read_state(account.config_dir)+ before = dict(state)+ shared: dict[str, str] = {}+ skipped: list[tuple[str, str]] = []++ for entry in USER_SETUP.get(platform, ()):+ source = native / entry.name+ target = account.config_dir / entry.name+ try:+ if entry.kind == "dir":+ if not source.is_dir():+ continue+ how, why = _share_dir(+ source,+ target,+ copy_fallback=entry.copy_fallback,+ whole=entry.whole,+ )+ else:+ if not source.is_file():+ continue+ how, why = _share_file(source, target, key=entry.name, fmt=entry.fmt, state=state)+ except OSError as exc: # pragma: no cover - defensive: a pane must open+ how, why = None, str(exc)+ if how is not None:+ shared[entry.name] = how+ elif why:+ skipped.append((entry.name, why))++ for merged in MERGED_KEYS.get(platform, ()):+ source = native / merged.name+ target = account.config_dir / merged.name+ label = f"{merged.name}#{merged.key}"+ try:+ how, why = _merge_key(source, target, merged.key, state_key=label, state=state)+ except OSError as exc: # pragma: no cover - defensive+ how, why = None, str(exc)+ if how is not None:+ shared[label] = how+ elif why:+ skipped.append((label, why))++ if state != before:+ _write_state(account.config_dir, state)++ fresh = {name: how for name, how in shared.items() if how != "current"}+ if fresh:+ logger.info(+ "Agent setup: {!r} now shares your own {} setup ({})",+ account.label,+ platform,+ ", ".join(f"{name} [{how}]" for name, how in fresh.items()),+ )+ for name, why in skipped:+ logger.info("Agent setup: {} stayed the account's own — {}", name, why)+ return ParityReport(shared=shared, skipped=tuple(skipped), redirected=True)+++__all__ = [+ "MERGED_KEYS",+ "STATE_FILE",+ "STATE_VERSION",+ "SUPERSEDED_SUFFIX",+ "USER_SETUP",+ "MergedKey",+ "ParityReport",+ "Shared",+ "ensure_parity",+]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 89cd9538e5..c3a385e084 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -39,6 +39,16 @@ process, so it is bounded deliberately):because agent TUIs treat an instant text+newline burst as a paste and inserta literal line break instead of submitting.+**A pane is the user's own CLI, not a stripped copy of it.** Whatever the user+gets by typing ``claude`` or ``codex`` in a terminal — their skills, subagents,+slash commands, plugins and connectors, hooks, output styles, global+instructions, default mode — a pane gets too. That is free while the CLI keeps+its own configuration directory, and it is NOT free for a pane running on an+added subscription, because switching accounts works by redirecting exactly that+directory (see ``_spawn_env`` and :mod:`jarvis.agent_config_parity`). Anything+this module opens must close that gap rather than ship a second, quieter version+of the CLI the user installed.+Platform notes: the PTY layer itself is already cross-platform behind``jarvis.terminal.backend`` (ConPTY on Windows, ptyprocess on POSIX, a clearlymessaged no-op where no PTY exists). What this module adds per platform is@@ -328,6 +338,25 @@ def _restore_key(space: resume_store.SnapshotWorkspace) -> str:return f"{space.session_id}|{resume_store.folder_key(space.folder)}"+def _redirected_home(term: Terminal) -> Path | None:+ """The config dir this pane's CLI will really run from, when it is not the+ machine's own.++ ``None`` for every pane that inherits the machine's configuration untouched+ — a plain terminal, a CLI that has no accounts, and the built-in login — and+ that is the case where a pane is already identical to an ordinary terminal.+ A path means the CLI has been redirected, which is what everything below has+ to compensate for.+ """+ if not term.account or term.agent not in AGENT_BINARIES:+ return None+ from jarvis import agent_accounts++ if not agent_accounts.env_overrides(term.agent, term.account): # type: ignore[arg-type]+ return None+ return agent_accounts.config_dir_for(term.agent, term.account) # type: ignore[arg-type]++def _spawn_env(term: Terminal) -> dict[str, str] | None:"""The child environment that puts this pane on its own subscription.@@ -336,20 +365,31 @@ def _spawn_env(term: Terminal) -> dict[str, str] | None:opens the switcher gets a spawn byte-for-byte identical to the one this appproduced before the feature existed.- Redirecting the CLI's config directory moves its user-level SETTINGS along- with its login, and the mode a session starts in is one of them. Without the- line below, a pane on an added account opened in the CLI's built-in fallback- — manual mode — no matter what the user had equipped globally, and every pane- had to be switched over by hand. Carrying those settings across is what makes- a pane start the way the same CLI starts in an ordinary terminal.+ Redirecting the CLI's config directory moves the CLI's whole USER LEVEL along+ with its login: its skills, subagents, slash commands, plugins and+ connectors, hooks, output styles, user memory file and settings all live in+ that directory. Left alone, a pane on an added account therefore ran a+ stripped version of the CLI the user has installed — no skills, no plugins,+ no global instructions, and the built-in fallback operating mode — while the+ same CLI in an ordinary terminal had all of it. A pane is supposed to BE that+ terminal, so the user's own setup is shared into the account's directory+ before the spawn (:mod:`jarvis.agent_config_parity`), and only what a shared+ settings file cannot carry falls back to the narrow per-key mode mirror.++ Filesystem work, so callers run it off the event loop."""- if not term.account or term.agent not in AGENT_BINARIES:+ if _redirected_home(term) is None:return None- from jarvis import agent_accounts-- if not agent_accounts.env_overrides(term.agent, term.account): # type: ignore[arg-type]- return None- agent_accounts.inherit_default_mode(term.agent, term.account) # type: ignore[arg-type]+ from jarvis import agent_accounts, agent_config_parity++ report = agent_config_parity.ensure_parity(term.agent, term.account) # type: ignore[arg-type]+ mode_file = agent_accounts.mode_file_name(term.agent) # type: ignore[arg-type]+ # Only when the account's settings file IS the user's file does sharing it+ # carry the mode too. A file the account has partly written itself was merely+ # filled in with the keys it lacked, and the mode may well be one of the keys+ # it already had — so the narrow per-key mirror still has work to do there.+ if report.shared.get(str(mode_file)) not in {"mirrored", "current"}:+ agent_accounts.inherit_default_mode(term.agent, term.account) # type: ignore[arg-type]return agent_accounts.spawn_env(term.agent, term.account) # type: ignore[arg-type]@@ -681,6 +721,11 @@ class Registry:# Held across reading the state AND writing it — see `_persist` for the# interleaving that otherwise loses a freshly discovered conversation id.self._persist_lock = asyncio.Lock()+ # (folder, account config dir) pairs already pre-trusted in this process.+ # A workspace of eight panes on one account would otherwise parse and+ # rewrite the same config file eight times — and that file grows to tens+ # of kilobytes on a heavy user (see jarvis.workspace.trust).+ self._pre_trusted: set[tuple[str, str]] = set()# ---------------------------------------------------------------- state@property@@ -1548,6 +1593,9 @@ class Registry:if viewer is not None:await viewer(code)+ # Off the event loop: getting the pane's account ready is filesystem+ # work (a few stat calls once it is in place — see `_prepare_spawn`).+ env = await asyncio.to_thread(self._prepare_spawn, term, session.folder)try:pty_session = await manager.spawn(shell_argv=argv,@@ -1577,6 +1625,44 @@ class Registry:await self._persist()return term+ def _prepare_spawn(self, term: Terminal, folder: str) -> dict[str, str] | None:+ """Everything this pane's agent needs on disk, then its environment.++ One thread hop for both, because both are filesystem work that has to+ finish before the process starts, and both exist for the same reason: a+ pane on an added subscription must open as the same session the user's+ own terminal opens (:func:`_spawn_env`), and it must not stop on a "do+ you trust this directory?" dialog on the way there.+ """+ self._pre_trust(term, folder)+ return _spawn_env(term)++ def _pre_trust(self, term: Terminal, folder: str) -> None:+ """Mark this folder trusted in the config dir THIS pane will run from.++ The workspace open already seeded the machine's own config, which covers+ every pane on the built-in login. A pane on an added account reads a+ different directory entirely, so without this it opens on the trust+ dialog — and a dialog nobody can answer from voice or the prompt bar is+ an agent that never starts. Once per folder and account per process.++ Never raises: an unseeded pane costs one click, a failed spawn costs the+ pane.+ """+ home = _redirected_home(term)+ if home is None:+ return+ key = (os.path.normcase(folder), os.path.normcase(str(home)))+ if key in self._pre_trusted:+ return+ self._pre_trusted.add(key)+ try:+ from jarvis.workspace.trust import ensure_trusted++ ensure_trusted(Path(folder), [term.agent], config_dirs={term.agent: [home]})+ except Exception as exc: # noqa: BLE001 - trust is a convenience+ logger.warning("Agentic IDE: pre-trust for {} failed: {}", term.name, exc)+def _schedule_lookup(self, owner: Session, term: Terminal, folder: str, started_at: float) -> None:diff --git a/jarvis/workspace/trust.py b/jarvis/workspace/trust.pyindex 7f045d226e..a286166ed2 100644--- a/jarvis/workspace/trust.py+++ b/jarvis/workspace/trust.py@@ -16,12 +16,22 @@ Both writes are atomic (temp file + ``os.replace``) and idempotent, and neverclobber unrelated keys. ``~/.claude.json`` is backed up once before the firstmutation. If a write fails we report it honestly — we never claim "skipped"when it wasn't.++``config_dirs`` covers the second place a CLI reads that file from. A terminal+running on an ADDED subscription resolves its whole configuration from the+account's own directory (:mod:`jarvis.agent_accounts`), so trust seeded into the+machine's default config is invisible to it and the pane opens on the very+dialog this module exists to skip. Callers that know which account a terminal+will run on pass its directory here; every other caller keeps the old behaviour+untouched."""+from __future__ import annotationsimport jsonimport loggingimport os+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom pathlib import Path@@ -37,10 +47,19 @@ class TrustResult:def ensure_trusted(- repo_root: Path, agents: list[str], *, home: Path | None = None+ repo_root: Path,+ agents: list[str],+ *,+ home: Path | None = None,+ config_dirs: Mapping[str, Iterable[Path]] | None = None,) -> list[TrustResult]:"""Mark ``repo_root`` as trusted for each agent. ``home`` overrides the home- dir (tests pass a tmp dir; production uses the real home + ``$CODEX_HOME``)."""+ dir (tests pass a tmp dir; production uses the real home + ``$CODEX_HOME``).++ ``config_dirs`` names EXTRA config directories per agent — the ones added+ subscriptions run from (see the module docstring). Each of them is seeded in+ addition to the machine's default, and contributes its own result, so a+ caller can see per directory whether the dialog will really be skipped."""test_mode = home is not Nonehome = home or Path.home()claude_cfg = home / ".claude.json"@@ -48,13 +67,18 @@ def ensure_trusted(codex_home = home / ".codex"else:codex_home = Path(os.environ.get("CODEX_HOME") or (home / ".codex"))+ codex_cfg = codex_home / "config.toml"results: list[TrustResult] = []for name in agents:if name == "claude":results.append(_trust_claude(repo_root, claude_cfg))+ for extra in _extra_configs(name, ".claude.json", claude_cfg, config_dirs):+ results.append(_trust_claude(repo_root, extra))elif name == "codex":- results.append(_trust_codex(repo_root, codex_home / "config.toml"))+ results.append(_trust_codex(repo_root, codex_cfg))+ for extra in _extra_configs(name, "config.toml", codex_cfg, config_dirs):+ results.append(_trust_codex(repo_root, extra))elif not _needs_trust(name):# A registered entry with no trust dialog to skip — a plain shell,# or a CLI that simply never asks. Nothing to write, and saying so@@ -65,6 +89,34 @@ def ensure_trusted(return results+def _extra_configs(+ agent: str,+ filename: str,+ default: Path,+ config_dirs: Mapping[str, Iterable[Path]] | None,+) -> list[Path]:+ """The additional trust files to seed for ``agent``, de-duplicated.++ A workspace can hold several panes on ONE added account, and seeding the+ same file once per pane would parse and rewrite a config that grows to tens+ of kilobytes. The machine's default is dropped too — it is already covered+ by the caller above, and a host started under a profile manager can name it+ here without meaning "do it twice".+ """+ if not config_dirs:+ return []+ seen: set[str] = {os.path.normcase(str(default))}+ extras: list[Path] = []+ for directory in config_dirs.get(agent, ()):+ candidate = Path(directory) / filename+ key = os.path.normcase(str(candidate))+ if key in seen:+ continue+ seen.add(key)+ extras.append(candidate)+ return extras++def _needs_trust(name: str) -> bool:"""Does the registry know this entry, and does it want folder trust seeded?"""from .agents import get_agent@@ -169,10 +221,7 @@ def _trust_codex(repo_root: Path, cfg: Path) -> TrustResult:doc["projects"] = projectsexisting = projects.get(native)- already = (- existing is not None- and dict(existing).get("trust_level") == "trusted"- )+ already = existing is not None and dict(existing).get("trust_level") == "trusted"if already:return TrustResult("codex", True, "noop", "already trusted")diff --git a/tests/unit/agentic_ide/test_account_spawn.py b/tests/unit/agentic_ide/test_account_spawn.pyindex 8cd606800f..c24c06ca19 100644--- a/tests/unit/agentic_ide/test_account_spawn.py+++ b/tests/unit/agentic_ide/test_account_spawn.py@@ -19,7 +19,7 @@ import pytestfrom jarvis import agent_accountsfrom jarvis.agentic_ide import session as session_mod-from jarvis.agentic_ide.session import Registry+from jarvis.agentic_ide.session import Registry, SessionErrorfrom tests.fakes.fake_pty_manager import FakePtyManager@@ -90,13 +90,20 @@ async def test_switching_the_default_does_not_move_a_running_pane(async def test_a_new_pane_after_the_switch_gets_the_new_account(registry: Registry, tmp_path: Path) -> None:+ """A terminal opened with no anchor is a NEW terminal, not a split.++ It therefore follows the active account. Inheriting from whatever pane+ happened to be last (the first version) made the switch reach nothing a user+ could predict: flipping to the second seat and opening a terminal still+ billed the first one.+ """await registry.start(str(tmp_path), [{"agent": "claude"}])second = agent_accounts.create_account("claude", "Second seat")agent_accounts.set_active("claude", second.id)added = await registry.add_terminal(agent="claude", anchor=None)- # No anchor was named, so the last pane is the anchor and its account is- # inherited — the switch reaches the panes that DON'T inherit one.- assert added.account == registry.session.terminals[0].account+ assert added.account == second.id+ # ...and the pane that was already open is untouched by it.+ assert registry.session.terminals[0].account == agent_accounts.builtin_id("claude")async def test_a_split_stays_on_the_account_its_anchor_runs_on(@@ -128,6 +135,114 @@ async def test_an_unknown_account_falls_back_instead_of_failing_the_pane(assert registry.session.terminals[0].account == agent_accounts.builtin_id("claude")+# ------------------------------------------------------- the workspace switch+++async def test_the_workspace_starts_on_the_stored_default(registry: Registry) -> None:+ """Nothing chosen here yet — so the answer is the machine's own default."""+ assert registry.active_account_id("claude") == agent_accounts.builtin_id("claude")+ assert registry.active_account_id("codex") == agent_accounts.builtin_id("codex")+++async def test_switching_in_the_workspace_moves_the_next_terminal(+ registry: Registry, tmp_path: Path+) -> None:+ """The whole point of the settings panel, as one assertion."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ await registry.set_active_account("claude", second.id)+ assert registry.active_account_id("claude") == second.id+ added = await registry.add_terminal(agent="claude")+ assert added.account == second.id+++async def test_switching_in_the_workspace_leaves_running_panes_alone(+ registry: Registry, tmp_path: Path+) -> None:+ """A running agent must never be moved onto a plan that has not seen it."""+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ pinned = registry.session.terminals[0].account+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.set_active_account("claude", second.id)+ assert registry.session.terminals[0].account == pinned+++async def test_the_switch_survives_a_restart(registry: Registry) -> None:+ """Written through to the stored default, so a fresh registry agrees.++ Two surfaces can switch this — the workspace and the app's account page —+ and a workspace-only pin would let them disagree the moment one was used.+ """+ second = agent_accounts.create_account("codex", "Second plan")+ await registry.set_active_account("codex", second.id)+ assert agent_accounts.active_account("codex").id == second.id+ assert Registry().active_account_id("codex") == second.id+++async def test_switching_to_an_account_of_another_cli_is_refused(+ registry: Registry,+) -> None:+ """A Claude account id means nothing to Codex — say so instead of guessing."""+ second = agent_accounts.create_account("claude", "Second seat")+ with pytest.raises(SessionError):+ await registry.set_active_account("codex", second.id)+ with pytest.raises(SessionError):+ await registry.set_active_account("claude", "claude:ghost")+++async def test_a_batch_of_terminals_opens_on_the_active_account(+ registry: Registry, tmp_path: Path+) -> None:+ """"Open five more" is five new terminals, so all five follow the switch."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ await registry.set_active_account("claude", second.id)+ created, capped = await registry.add_terminals(3, agent="claude")+ assert capped is False+ assert [t.account for t in created] == [second.id] * 3+++async def test_a_split_still_stays_on_its_anchor_after_a_switch(+ registry: Registry, tmp_path: Path+) -> None:+ """The switch governs NEW terminals; a split is "another one of these"."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ anchor = registry.session.terminals[0]+ await registry.set_active_account("claude", second.id)+ split = await registry.add_terminal(anchor=anchor.name, direction="down")+ assert split.account == anchor.account+++async def test_the_state_names_the_active_account_in_words(+ registry: Registry, tmp_path: Path+) -> None:+ """An id is not something anybody can read back — the UI shows the label."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ await registry.set_active_account("claude", second.id)+ claude = next(row for row in registry.state()["accounts"] if row["agent"] == "claude")+ assert claude["active_account"] == second.id+ assert claude["active_label"] == "Second seat"+ assert claude["display_name"] == "Claude Code"+ # Built-in plus the added one — what tells a UI there is anything to choose.+ assert claude["account_count"] == 2+++async def test_a_terminal_opened_after_the_switch_spawns_on_that_config_dir(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """End to end: the switch has to reach the child environment, or it is talk."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ await registry.set_active_account("claude", second.id)+ added = await registry.add_terminal(agent="claude")+ await _attach(registry, added.name)+ env = _env_of(fake_pty, -1)+ assert env is not None+ assert env["CLAUDE_CONFIG_DIR"] == str(second.config_dir)++# --------------------------------------------------------------- the spawn@@ -168,6 +283,80 @@ async def test_the_spawn_environment_keeps_PATH(assert env["CODEX_HOME"] == str(second.config_dir)+async def test_a_pane_on_an_added_account_still_runs_the_users_own_setup(+ registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The switch must not cost the user their CLI.++ Redirecting the config dir moves the CLI's whole user level with it, so+ without provisioning a pane on a second subscription opens with none of the+ user's skills, plugins, hooks or global instructions — a quieter, different+ product than the same CLI in a terminal. Asserted at the spawn, because the+ provisioning is only worth anything if it happens before the agent starts.+ """+ own = Path(agent_accounts.native_dir("claude"))+ (own / "skills" / "git-rescue").mkdir(parents=True)+ (own / "skills" / "git-rescue" / "SKILL.md").write_text("# rescue\n", encoding="utf-8")+ (own / "CLAUDE.md").write_text("Answer in plain language.\n", encoding="utf-8")++ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "account": second.id}])+ await _attach(registry, registry.session.terminals[0].name)++ assert (second.config_dir / "skills" / "git-rescue" / "SKILL.md").is_file()+ assert (second.config_dir / "CLAUDE.md").is_file()+ # ...and the login it was opened for is still the only identity in there.+ assert not (second.config_dir / ".credentials.json").exists()+++async def test_a_pane_pre_trusts_the_folder_in_its_own_account_directory(+ registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A CLI reads trust from the directory it was pointed at.++ Seeded only into the machine's default, an added-account pane opens on the+ "do you trust this directory?" dialog — and a dialog nobody can answer from+ voice or the prompt bar is an agent that never starts.+ """+ from jarvis.workspace import trust++ seen: list[tuple[str, list[str], dict[str, list[Path]] | None]] = []++ def _record(root: Path, agents: list[str], **kwargs: object) -> list[object]:+ seen.append((str(root), agents, kwargs.get("config_dirs"))) # type: ignore[arg-type]+ return []++ monkeypatch.setattr(trust, "ensure_trusted", _record)+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "account": second.id}])+ await _attach(registry, registry.session.terminals[0].name)++ seeded = [call for call in seen if call[2]]+ assert seeded, "the pane's own account directory was never pre-trusted"+ assert seeded[0][2] == {"claude": [second.config_dir]}+ # Once per folder and account, however many panes attach to it.+ await _attach(registry, registry.session.terminals[0].name)+ assert len([call for call in seen if call[2]]) == 1+++async def test_a_pane_on_the_builtin_login_is_not_pre_trusted_twice(+ registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Nothing was redirected, so the workspace open already covered it."""+ from jarvis.workspace import trust++ seen: list[dict[str, list[Path]] | None] = []++ def _record(_root: Path, _agents: list[str], **kwargs: object) -> list[object]:+ seen.append(kwargs.get("config_dirs")) # type: ignore[arg-type]+ return []++ monkeypatch.setattr(trust, "ensure_trusted", _record)+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ await _attach(registry, registry.session.terminals[0].name)+ assert [call for call in seen if call] == []++async def test_two_panes_can_run_two_different_subscriptions_at_once(registry: Registry, fake_pty: FakePtyManager, tmp_path: Path) -> None:diff --git a/tests/unit/test_agent_config_parity.py b/tests/unit/test_agent_config_parity.pynew file mode 100644index 0000000000..a2dd92f0fd--- /dev/null+++ b/tests/unit/test_agent_config_parity.py@@ -0,0 +1,372 @@+"""A pane on an added subscription runs the user's OWN CLI setup.++The bug these pin down was invisible and total: switching a pane to a second+subscription redirects the CLI's config directory, that directory carries the+whole user level of the CLI, and so the pane silently lost every skill, every+plugin, every hook and the user's global instructions. It still answered — it+just answered as a different, emptier product than the same CLI in a terminal.++So what is asserted here is not "a function ran" but the three properties that+decide whether the fix is real:++1. the user's setup ARRIVES in the redirected directory (and keeps arriving+ after they add something new),+2. the account's IDENTITY is never touched on the way — no credential, no+ conversation record, and no value the account set for itself,+3. every host can do it: a symlink where symlinks work, a junction on Windows+ where they need a privilege, and a copy where neither is possible.+"""++from __future__ import annotations++import json+import os+from pathlib import Path++import pytest++from jarvis import agent_accounts, agent_config_parity+from jarvis.agent_config_parity import ensure_parity++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A throwaway store, account root and "user's own config" — never the real ones."""+ monkeypatch.setattr(agent_accounts, "_store_path", lambda: tmp_path / "accounts.json")+ monkeypatch.setattr(agent_accounts, "_accounts_root", lambda: tmp_path / "dirs")+ monkeypatch.setattr(+ agent_accounts, "_native_dir", lambda platform: tmp_path / "native" / platform+ )+ return tmp_path+++def native(tmp_path: Path) -> Path:+ """The user's own Claude Code config directory, with a real setup in it."""+ home = tmp_path / "native" / "claude"+ (home / "skills" / "git-rescue").mkdir(parents=True)+ (home / "skills" / "git-rescue" / "SKILL.md").write_text("# rescue\n", encoding="utf-8")+ (home / "agents").mkdir()+ (home / "agents" / "code-reviewer.md").write_text("reviewer\n", encoding="utf-8")+ (home / "CLAUDE.md").write_text("Answer in plain language.\n", encoding="utf-8")+ (home / "settings.json").write_text(+ json.dumps({"model": "opus", "enabledPlugins": {"github@official": True}}),+ encoding="utf-8",+ )+ # Identity and conversation record — present so a test can prove they are+ # NOT what gets shared.+ (home / ".credentials.json").write_text('{"token": "user-secret"}', encoding="utf-8")+ (home / "projects").mkdir()+ (home / "projects" / "a.jsonl").write_text("{}\n", encoding="utf-8")+ return home+++def _account(label: str = "Second seat") -> agent_accounts.AgentAccount:+ return agent_accounts.create_account("claude", label)+++def _links_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:+ """A host that refuses every kind of link — Windows without Developer Mode+ and without the junction API, or a filesystem that has neither."""++ def _no_symlink(*_args: object, **_kwargs: object) -> None:+ raise OSError("symlinks are not available here")++ monkeypatch.setattr(os, "symlink", _no_symlink)+ monkeypatch.setattr(agent_config_parity, "_link", lambda *_a, **_k: None)+++# ------------------------------------------------------------- the setup arrives+++def test_an_added_account_sees_the_users_skills(native: Path) -> None:+ """The reported bug, as one assertion: 93 skills in a terminal, none in a pane."""+ account = _account()+ report = ensure_parity("claude", account.id)+ assert "skills" in report.shared+ assert (account.config_dir / "skills" / "git-rescue" / "SKILL.md").is_file()+++def test_the_users_subagents_settings_and_memory_arrive_too(native: Path) -> None:+ """Skills were the symptom; the whole user level is the fix."""+ account = _account()+ ensure_parity("claude", account.id)+ assert (account.config_dir / "agents" / "code-reviewer.md").is_file()+ assert (account.config_dir / "CLAUDE.md").read_text(encoding="utf-8").startswith("Answer")+ settings = json.loads((account.config_dir / "settings.json").read_text(encoding="utf-8"))+ assert settings["enabledPlugins"] == {"github@official": True}+++def test_a_skill_added_later_shows_up_without_a_second_copy(native: Path) -> None:+ """Shared, not snapshotted — a link means today's install is in yesterday's pane.++ On a host that had to copy instead, the re-run is what carries it, which is+ why parity is refreshed before every spawn rather than once per account.+ """+ account = _account()+ ensure_parity("claude", account.id)+ (native / "skills" / "brand-new").mkdir()+ (native / "skills" / "brand-new" / "SKILL.md").write_text("# new\n", encoding="utf-8")+ ensure_parity("claude", account.id)+ assert (account.config_dir / "skills" / "brand-new" / "SKILL.md").is_file()+++def test_a_global_settings_change_follows_through(native: Path) -> None:+ account = _account()+ ensure_parity("claude", account.id)+ (native / "settings.json").write_text(json.dumps({"model": "sonnet"}), encoding="utf-8")+ ensure_parity("claude", account.id)+ settings = json.loads((account.config_dir / "settings.json").read_text(encoding="utf-8"))+ assert settings == {"model": "sonnet"}+++def test_the_user_scope_mcp_servers_are_merged_without_the_identity(native: Path) -> None:+ """Connectors live in a document that also holds the login — one key, not the file."""+ (native / ".claude.json").write_text(+ json.dumps({"mcpServers": {"chrome": {"command": "chrome-mcp"}}, "userID": "user-1"}),+ encoding="utf-8",+ )+ account = _account()+ account.config_dir.mkdir(parents=True, exist_ok=True)+ (account.config_dir / ".claude.json").write_text(+ json.dumps({"userID": "account-2", "oauthAccount": {"emailAddress": "[email protected]"}}),+ encoding="utf-8",+ )+ report = ensure_parity("claude", account.id)+ assert report.shared[".claude.json#mcpServers"] == "merged"+ doc = json.loads((account.config_dir / ".claude.json").read_text(encoding="utf-8"))+ assert doc["mcpServers"] == {"chrome": {"command": "chrome-mcp"}}+ # The account's own identity is still the account's own.+ assert doc["userID"] == "account-2"+ assert doc["oauthAccount"] == {"emailAddress": "[email protected]"}+++def test_codex_shares_its_config_and_prompts(tmp_path: Path) -> None:+ """The same promise for the other CLI — never a Claude-only fix (AP-21)."""+ home = tmp_path / "native" / "codex"+ (home / "prompts").mkdir(parents=True)+ (home / "prompts" / "review.md").write_text("review\n", encoding="utf-8")+ (home / "config.toml").write_text(+ '[mcp_servers.chrome]\ncommand = "chrome-mcp"\n', encoding="utf-8"+ )+ (home / "auth.json").write_text('{"token": "codex-secret"}', encoding="utf-8")+ account = agent_accounts.create_account("codex", "Second plan")+ report = ensure_parity("codex", account.id)+ assert "config.toml" in report.shared+ assert (account.config_dir / "prompts" / "review.md").is_file()+ assert "mcp_servers" in (account.config_dir / "config.toml").read_text(encoding="utf-8")+ assert not (account.config_dir / "auth.json").exists()+++# ------------------------------------------------------------- identity is safe+++def test_the_login_and_the_conversation_record_are_never_shared(native: Path) -> None:+ """The one thing that must never travel: a copied OAuth token dies in place,+ and a shared conversation record would hand one account's history to another.+ """+ account = _account()+ ensure_parity("claude", account.id)+ assert not (account.config_dir / ".credentials.json").exists()+ assert not (account.config_dir / "projects").exists()+++def test_a_value_the_account_set_for_itself_is_left_alone(native: Path) -> None:+ """A pane may change its own settings; the next spawn must not undo that.++ And the other half, which is what makes this a fix rather than a trade: the+ keys the account is MISSING still arrive. An account whose settings file a+ pane once touched would otherwise keep its theme and lose every plugin — the+ exact half-fixed state this was measured in on 2026-07-27.+ """+ account = _account()+ ensure_parity("claude", account.id)+ own = account.config_dir / "settings.json"+ own.write_text(json.dumps({"model": "haiku", "theme": "dark"}), encoding="utf-8")+ report = ensure_parity("claude", account.id)+ settings = json.loads(own.read_text(encoding="utf-8"))+ assert settings["model"] == "haiku" # the pane's own choice, untouched+ assert settings["theme"] == "dark"+ assert settings["enabledPlugins"] == {"github@official": True} # ...and the user's+ assert report.shared["settings.json"] == "merged"+++def test_a_nested_setting_the_account_lacks_is_filled_in(native: Path) -> None:+ """Top-level only would drop the user's permissions behind an existing key."""+ (native / "settings.json").write_text(+ json.dumps({"permissions": {"defaultMode": "plan", "allow": ["Bash(ls:*)"]}}),+ encoding="utf-8",+ )+ account = _account()+ own = account.config_dir / "settings.json"+ own.parent.mkdir(parents=True, exist_ok=True)+ own.write_text(json.dumps({"permissions": {"defaultMode": "acceptEdits"}}), encoding="utf-8")+ ensure_parity("claude", account.id)+ permissions = json.loads(own.read_text(encoding="utf-8"))["permissions"]+ assert permissions["defaultMode"] == "acceptEdits" # the account's own+ assert permissions["allow"] == ["Bash(ls:*)"] # the user's, no longer missing+++def test_the_users_memory_file_is_not_merged_line_by_line(native: Path) -> None:+ """Plain text has no keys — an account file of its own stays its own."""+ account = _account()+ own = account.config_dir / "CLAUDE.md"+ own.parent.mkdir(parents=True, exist_ok=True)+ own.write_text("Account house style.\n", encoding="utf-8")+ report = ensure_parity("claude", account.id)+ assert own.read_text(encoding="utf-8") == "Account house style.\n"+ assert any(name == "CLAUDE.md" for name, _why in report.skipped)+++def test_a_merged_file_is_not_replaced_wholesale_on_the_next_run(native: Path) -> None:+ """The hybrid is nobody's copy, so it must never be mistaken for a mirror."""+ account = _account()+ own = account.config_dir / "settings.json"+ own.parent.mkdir(parents=True, exist_ok=True)+ own.write_text(json.dumps({"model": "haiku"}), encoding="utf-8")+ ensure_parity("claude", account.id)+ second = ensure_parity("claude", account.id)+ assert json.loads(own.read_text(encoding="utf-8"))["model"] == "haiku"+ assert second.shared["settings.json"] == "current"+++def test_an_account_skill_of_its_own_survives_the_merge(native: Path) -> None:+ """What the account has stays; only what it is MISSING is shared in."""+ account = _account()+ theirs = account.config_dir / "skills" / "account-only"+ theirs.mkdir(parents=True)+ (theirs / "SKILL.md").write_text("account", encoding="utf-8")+ ensure_parity("claude", account.id)+ assert (theirs / "SKILL.md").is_file()+ assert (account.config_dir / "skills" / "git-rescue" / "SKILL.md").is_file()+++def test_a_plugin_tree_the_cli_half_filled_is_replaced_as_a_whole(native: Path) -> None:+ """Which plugins are ACTIVE lives in state files beside the marketplaces they+ name, so the user's marketplaces next to the account's own state list nothing+ the CLI can load. What was there is kept beside it, not deleted.+ """+ (native / "plugins" / "marketplaces" / "official").mkdir(parents=True)+ (native / "plugins" / "installed_plugins.json").write_text("{}", encoding="utf-8")+ account = _account()+ stale = account.config_dir / "plugins" / "marketplaces" / "official"+ stale.mkdir(parents=True)+ ensure_parity("claude", account.id)+ assert (account.config_dir / "plugins" / "installed_plugins.json").exists()+ assert (+ account.config_dir / ("plugins" + agent_config_parity.SUPERSEDED_SUFFIX)+ ).is_dir()+++def test_the_superseded_copy_is_only_moved_aside_once(native: Path) -> None:+ """It runs before every spawn — a folder per spawn would be a leak."""+ (native / "plugins").mkdir(parents=True)+ account = _account()+ (account.config_dir / "plugins").mkdir(parents=True)+ ensure_parity("claude", account.id)+ ensure_parity("claude", account.id)+ stacked = list(account.config_dir.glob("plugins*" + agent_config_parity.SUPERSEDED_SUFFIX))+ assert len(stacked) == 1+++# ----------------------------------------------------------------- no redirect+++def test_the_builtin_login_is_left_completely_alone(native: Path) -> None:+ """Nothing was redirected, so nothing was lost, so nothing is provisioned.++ The promise to everyone holding a single subscription: their panes spawn+ exactly as they did before any of this existed.+ """+ report = ensure_parity("claude", agent_accounts.builtin_id("claude"))+ assert report.redirected is False+ assert report.shared == {}+++def test_an_unknown_account_is_a_no_op(native: Path) -> None:+ assert ensure_parity("claude", "claude:ghost").redirected is False+ assert ensure_parity("claude", None).redirected is False+++def test_a_machine_with_no_setup_of_its_own_is_not_a_failure(tmp_path: Path) -> None:+ """A fresh install has no user-level config — there is nothing to share."""+ account = _account()+ report = ensure_parity("claude", account.id)+ assert report.redirected is True+ assert report.shared == {}+ assert report.skipped == ()+++# ------------------------------------------------------------------- every host+++def test_a_host_without_links_copies_the_users_setup_instead(+ native: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Windows without Developer Mode, or a filesystem with no reparse points."""+ _links_unavailable(monkeypatch)+ account = _account()+ report = ensure_parity("claude", account.id)+ assert report.shared["skills"] == "copied"+ assert (account.config_dir / "skills" / "git-rescue" / "SKILL.md").is_file()+++def test_a_tree_that_must_not_be_copied_is_reported_instead_of_faked(+ native: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A copied plugin tree goes stale invisibly — "missing, and said so" is better."""+ (native / "plugins" / "marketplaces").mkdir(parents=True)+ _links_unavailable(monkeypatch)+ account = _account()+ report = ensure_parity("claude", account.id)+ assert "plugins" not in report.shared+ assert any(name == "plugins" for name, _why in report.skipped)+++def test_running_it_twice_changes_nothing(native: Path) -> None:+ """It runs before every spawn, so a second run must be a handful of stats."""+ account = _account()+ ensure_parity("claude", account.id)+ second = ensure_parity("claude", account.id)+ assert set(second.shared) >= {"skills", "settings.json", "CLAUDE.md"}+ assert set(second.shared.values()) == {"current"}+++def test_a_link_that_was_replaced_by_a_copy_is_re_shared(native: Path) -> None:+ """Self-healing: several components write into a config dir with an atomic+ replace, which silently turns a share into a private copy."""+ account = _account()+ ensure_parity("claude", account.id)+ shared_file = account.config_dir / "CLAUDE.md"+ shared_file.write_text("Answer in plain language.\n", encoding="utf-8")+ (native / "CLAUDE.md").write_text("New house style.\n", encoding="utf-8")+ ensure_parity("claude", account.id)+ assert shared_file.read_text(encoding="utf-8") == "New house style.\n"+++def test_a_dangling_link_is_repaired_rather_than_inherited(+ native: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The user deleted the folder we pointed at; the pane must not keep a stub."""+ account = _account()+ ensure_parity("claude", account.id)+ target = account.config_dir / "skills"+ if not os.path.lexists(target): # pragma: no cover - defensive+ pytest.skip("nothing was shared on this host")+ # Re-point the user's own skills at a fresh folder, leaving the old link+ # dangling exactly as a deletion would.+ monkeypatch.setattr(agent_config_parity, "_link", lambda *_a, **_k: None)+ ensure_parity("claude", account.id)+ assert (native / "skills").is_dir()+++def test_it_never_raises_on_a_host_that_refuses_everything(+ native: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A pane must open even when nothing can be provisioned for it."""+ _links_unavailable(monkeypatch)+ monkeypatch.setattr(agent_config_parity, "_copy", lambda *_a, **_k: None)+ account = _account()+ report = ensure_parity("claude", account.id)+ assert report.redirected is True+ assert report.skipped # honestly reported, not silently emptydiff --git a/tests/unit/workspace/test_trust.py b/tests/unit/workspace/test_trust.pyindex c8f9ed1b46..f8f3bdd58a 100644--- a/tests/unit/workspace/test_trust.py+++ b/tests/unit/workspace/test_trust.py@@ -2,7 +2,6 @@from __future__ import annotationsimport json-import sysimport tomllibfrom pathlib import Path@@ -160,6 +159,55 @@ def test_codex_falls_through_when_the_config_is_unreadable(tmp_path: Path) -> Noassert res.ok is False+def test_an_added_accounts_config_dir_is_trusted_as_well(tmp_path: Path) -> None:+ """A terminal on a second subscription reads a different config directory.++ Seeded only into the machine's default, it opens on the very dialog this+ module exists to skip — so a caller that knows which account a terminal will+ run on can name its directory and get both seeded.+ """+ home = tmp_path / "home"+ home.mkdir()+ repo = _repo(tmp_path)+ account = tmp_path / "accounts" / "second-seat"++ results = ensure_trusted(+ repo, ["claude"], home=home, config_dirs={"claude": [account]}+ )++ assert [r.ok for r in results] == [True, True]+ for cfg in (home / ".claude.json", account / ".claude.json"):+ data = json.loads(cfg.read_text(encoding="utf-8"))+ assert data["projects"][str(repo)]["hasTrustDialogAccepted"] is True+++def test_the_same_account_named_twice_is_only_seeded_once(tmp_path: Path) -> None:+ """Eight panes on one account must not parse and rewrite one config eight times."""+ home = tmp_path / "home"+ home.mkdir()+ account = tmp_path / "accounts" / "second-seat"+ results = ensure_trusted(+ _repo(tmp_path),+ ["codex"],+ home=home,+ config_dirs={"codex": [account, account, home / ".codex"]},+ )+ # The machine's default plus the account — never the default a second time.+ assert len(results) == 2+ assert tomllib.loads((account / "config.toml").read_text(encoding="utf-8"))["projects"]+++def test_an_account_directory_for_another_agent_is_ignored(tmp_path: Path) -> None:+ """A Claude config dir means nothing to Codex — it must not be written to."""+ home = tmp_path / "home"+ home.mkdir()+ account = tmp_path / "accounts" / "claude-seat"+ ensure_trusted(+ _repo(tmp_path), ["codex"], home=home, config_dirs={"claude": [account]}+ )+ assert not account.exists()++def test_test_mode_ignores_real_codex_home_env(tmp_path: Path, monkeypatch) -> None:# A stray CODEX_HOME must NOT redirect the write away from the tmp home.monkeypatch.setenv("CODEX_HOME", str(tmp_path / "REAL_DO_NOT_TOUCH"))