diff --git a/CHANGELOG.md b/CHANGELOG.md index f9dd58b..dd88c58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - `dyro dispatch backends` 在 Grok CLI 只配置了 API key、`grok models` 未打印会话登录句时,也会识别为已认证;CLI 明确表示未登录时仍视为未认证。 +- 修复 macOS 上 `/tmp` 与 `/private/tmp`(以及 `/var` 与 `/private/var`)路径写法不一致时,技能清单被误判过期、进程内状态锁重入死锁,以及蓝图加入与全局主目录路径对不齐的问题;旧版清单中的原写法仍可识别。 ## 0.7.17 - 2026-11-14 diff --git a/src/dyro/blueprint.py b/src/dyro/blueprint.py index 83ff845..9a1d2e5 100644 --- a/src/dyro/blueprint.py +++ b/src/dyro/blueprint.py @@ -19,6 +19,7 @@ from .errors import DyroError, ValidationError from .onboarding import RepositoryInput, render_config from .process import git, require_ok, run +from .read_limits import canonical_entry_path from .state import atomic_write_text, exclusive_lock from .workspace import STORAGE_MODES, Line, create_line, doctor, get_line, is_missing_origin_finding @@ -453,7 +454,9 @@ def load_blueprint_source( def default_join_root(blueprint: Blueprint) -> Path: override = os.environ.get("DYRO_PROJECTS_HOME", "").strip() parent = Path(override).expanduser() if override else Path.home() / "DyroProjects" - return (parent / blueprint.suggested_directory).absolute() + # Rewrite trusted macOS /tmp|/var aliases only; keep user symlinks visible + # to preflight_join_plan / _reject_symlink_components. + return canonical_entry_path(parent / blueprint.suggested_directory) def build_join_plan( @@ -472,7 +475,7 @@ def build_join_plan( f"蓝图中没有开发线 {selected_line};可选:{', '.join(sorted(blueprint.lines))}" ) from exc root = ( - Path(target).expanduser().absolute() + canonical_entry_path(Path(target).expanduser()) if target is not None else default_join_root(blueprint) ) diff --git a/src/dyro/hub.py b/src/dyro/hub.py index c3dda3c..13497f0 100644 --- a/src/dyro/hub.py +++ b/src/dyro/hub.py @@ -9,7 +9,7 @@ from .config import Config, load, validate_id from .errors import DyroError, ValidationError -from .read_limits import ReadBudget, ReadLimitCode, ReadLimitError +from .read_limits import ReadBudget, ReadLimitCode, ReadLimitError, canonical_entry_path from .state import atomic_write_text, exclusive_lock @@ -179,15 +179,15 @@ def unregistered_workspace_error(name: str, names: tuple[str, ...]) -> DyroError def registry_home() -> Path: override = os.environ.get("DYRO_HOME", "").strip() if override: - return Path(override).expanduser().absolute() + return canonical_entry_path(Path(override).expanduser()) if os.name == "nt": base = os.environ.get("APPDATA", "").strip() if base: - return Path(base).expanduser().absolute() / "Dyro" + return canonical_entry_path(Path(base).expanduser()) / "Dyro" base = os.environ.get("XDG_CONFIG_HOME", "").strip() if base: - return Path(base).expanduser().absolute() / "dyro" - return Path.home() / ".config" / "dyro" + return canonical_entry_path(Path(base).expanduser()) / "dyro" + return canonical_entry_path(Path.home() / ".config" / "dyro") def _registry_path() -> Path: diff --git a/src/dyro/integrations/manager.py b/src/dyro/integrations/manager.py index 8025ac1..877f744 100644 --- a/src/dyro/integrations/manager.py +++ b/src/dyro/integrations/manager.py @@ -20,6 +20,7 @@ ReadLimitCode, ReadLimitError, bounded_directory_names, + canonical_entry_path, trusted_system_alias_target, ) from ..state import atomic_write_text, exclusive_lock, fsync_directory @@ -217,7 +218,7 @@ def _absolute_path(value: Path, label: str) -> Path: expanded = value.expanduser() if not expanded.is_absolute(): raise ValidationError(f"{label} 必须是绝对路径:{value}") - return Path(os.path.normpath(expanded)) + return canonical_entry_path(Path(os.path.normpath(expanded))) def _dyro_home(override: Path | None) -> Path: @@ -682,7 +683,12 @@ def _inspect_avatar( str(avatar.readlink()) if avatar.is_symlink() else str(avatar.resolve()), ) if avatar.is_dir() and not avatar.is_symlink(): - if recorded is not None and str(recorded.get("path")) == str(avatar): + recorded_path = recorded.get("path") if recorded is not None else None + if ( + isinstance(recorded_path, str) + and canonical_entry_path(Path(recorded_path)) + == canonical_entry_path(avatar) + ): return AvatarStatus(host, avatar, "drifted", "分身被替换为普通目录") # Owned legacy copy may still sit here before migration. return AvatarStatus( @@ -723,9 +729,13 @@ def _legacy_owned_copy( except ValidationError: return None target = Path(str(manifest["target"])) - if expected_target is not None and target != expected_target: + if expected_target is not None and canonical_entry_path(target) != canonical_entry_path( + expected_target + ): return None - if allowed_targets is not None and target not in allowed_targets: + if allowed_targets is not None and canonical_entry_path(target) not in { + canonical_entry_path(path) for path in allowed_targets + }: return None if target.is_symlink() or not target.is_dir(): return None @@ -899,7 +909,11 @@ def integration_status( tuple(avatar_rows), ) - if manifest["mirror"] != str(mirror): + stored_mirror = manifest["mirror"] + if ( + not isinstance(stored_mirror, str) + or canonical_entry_path(Path(stored_mirror)) != canonical_entry_path(mirror) + ): return IntegrationStatus( requested, IntegrationState.STALE_MANIFEST, @@ -1186,7 +1200,11 @@ def _restored_owned_installation( if manifest_path.read_text(encoding="utf-8") != original_manifest_text: return False manifest = _parse_manifest(manifest_path, spec) - if manifest["mirror"] != str(mirror): + stored_mirror = manifest["mirror"] + if ( + not isinstance(stored_mirror, str) + or canonical_entry_path(Path(stored_mirror)) != canonical_entry_path(mirror) + ): return False if _inventory(mirror) != manifest["files"]: return False @@ -1279,7 +1297,8 @@ def _install_avatars( if avatar.exists() or avatar.is_symlink(): if ( legacy_target is not None - and avatar == legacy_target + and canonical_entry_path(avatar) + == canonical_entry_path(legacy_target) and avatar in allowed and avatar.is_dir() and not avatar.is_symlink() diff --git a/src/dyro/read_limits.py b/src/dyro/read_limits.py index ab63446..8956abc 100644 --- a/src/dyro/read_limits.py +++ b/src/dyro/read_limits.py @@ -188,16 +188,26 @@ def trusted_system_alias_target(path: Path) -> Path | None: return None +def canonical_entry_path(path: Path) -> Path: + """Absolute path with trusted macOS ``/tmp`` / ``/var`` aliases rewritten. + + Does not follow arbitrary symlinks. Use this when two spellings of the same + entry directory must compare equal (for example ``/tmp/x`` vs ``/private/tmp/x``). + """ + absolute = path.absolute() + if len(absolute.parts) > 1: + target = trusted_system_alias_target(Path(*absolute.parts[:2])) + if target is not None: + return target.joinpath(*absolute.parts[2:]) + return absolute + + def _checked_absolute(path: Path, label: str) -> Path: if any(part in {".", ".."} for part in path.parts): raise ValidationError(f"{label} 不得包含点路径分量") - absolute = path.absolute() + absolute = canonical_entry_path(path) if not absolute.is_absolute() or not absolute.anchor: raise ValidationError(f"{label} 必须是绝对路径") - if len(absolute.parts) > 1: - target = trusted_system_alias_target(Path(*absolute.parts[:2])) - if target is not None: - absolute = target.joinpath(*absolute.parts[2:]) return absolute diff --git a/src/dyro/state.py b/src/dyro/state.py index b12b6f2..74d8af6 100644 --- a/src/dyro/state.py +++ b/src/dyro/state.py @@ -9,6 +9,7 @@ from typing import Iterator, TextIO from .errors import DyroError +from .read_limits import canonical_entry_path _LOCK_CONDITION = threading.Condition() @@ -200,7 +201,7 @@ def _unlock(handle: TextIO) -> None: @contextmanager def exclusive_lock(path: Path, *, timeout_seconds: float = 15.0) -> Iterator[None]: """Acquire a process-safe, thread-reentrant lock for a small state transition.""" - resolved = path.absolute() + resolved = canonical_entry_path(path) owner = threading.get_ident() deadline = time.monotonic() + timeout_seconds reentrant = False diff --git a/tests/test_blueprint.py b/tests/test_blueprint.py index a04f8d3..be8c676 100644 --- a/tests/test_blueprint.py +++ b/tests/test_blueprint.py @@ -13,10 +13,12 @@ build_join_plan, load_blueprint_source, parse_blueprint, + preflight_join_plan, ) from dyro.cli import main from dyro.config import load from dyro.errors import DyroError, ValidationError +from dyro.read_limits import canonical_entry_path from dyro.workspace import doctor, get_line, is_missing_origin_finding from .support import shell @@ -411,6 +413,39 @@ def test_local_directory_source_rejects_symlinked_path_components(self) -> None: with self.assertRaisesRegex(DyroError, "不能经过符号链接"): load_blueprint_source(str(source), blueprint_file="config/team.toml") + @unittest.skipUnless( + Path("/tmp").is_symlink() and Path("/tmp").resolve() == Path("/private/tmp"), + "requires the macOS /tmp system alias", + ) + def test_join_plan_root_resolves_tmp_alias_spelling(self) -> None: + with tempfile.TemporaryDirectory(prefix="dyro-join-alias-", dir="/tmp") as temporary: + canonical = Path(temporary).resolve() + try: + alias = Path("/tmp") / canonical.relative_to("/private/tmp") + except ValueError: + self.skipTest("temporary directory is not below /private/tmp") + target = alias / "workspace" + document = load_blueprint_source(str(self.blueprint_file)) + plan = build_join_plan(document, target=target, line_id=None) + self.assertEqual(plan.root, canonical_entry_path(target)) + self.assertEqual(plan.root, canonical / "workspace") + + def test_join_refuses_symlinked_target_root(self) -> None: + real = self.parent / "real-workspace" + real.mkdir() + link = self.parent / "workspace-link" + link.symlink_to(real, target_is_directory=True) + plan = build_join_plan( + load_blueprint_source(str(self.blueprint_file)), + target=link, + line_id=None, + ) + self.assertEqual(plan.root, canonical_entry_path(link)) + self.assertTrue(plan.root.is_symlink()) + with self.assertRaisesRegex(DyroError, "目标工作区不能是符号链接"): + preflight_join_plan(plan) + self.assertEqual(list(real.iterdir()), []) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_hub.py b/tests/test_hub.py index f3f6256..a023612 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -42,6 +42,7 @@ unique_registered_alias, workspace_alias_retargets_root, ) +from dyro.read_limits import canonical_entry_path from dyro.tooling import ( ToolPreferences, ToolState, @@ -93,7 +94,7 @@ def test_numeric_repository_id_wins_over_index(self) -> None: class RegistryTests(unittest.TestCase): def setUp(self) -> None: self.tmp = tempfile.TemporaryDirectory(prefix="dyro-hub-") - self.base = Path(self.tmp.name) + self.base = canonical_entry_path(Path(self.tmp.name)) self.state = self.base / "state" self.workspace = self.base / "workspace" self.workspace.mkdir() @@ -280,6 +281,20 @@ def test_malformed_registry_rejects_non_string_alias(self) -> None: with self.assertRaisesRegex(Exception, "别名"): load_registry() + @unittest.skipUnless( + Path("/tmp").is_symlink() and Path("/tmp").resolve() == Path("/private/tmp"), + "requires the macOS /tmp system alias", + ) + def test_registry_home_rewrites_tmp_alias_spelling(self) -> None: + with tempfile.TemporaryDirectory(prefix="dyro-hub-alias-", dir="/tmp") as temporary: + canonical = Path(temporary).resolve() + try: + alias = Path("/tmp") / canonical.relative_to("/private/tmp") + except ValueError: + self.skipTest("temporary directory is not below /private/tmp") + with patch.dict(os.environ, {"DYRO_HOME": str(alias)}): + self.assertEqual(registry_home(), canonical) + class HubCliTests(WorkspaceCase): def setUp(self) -> None: diff --git a/tests/test_integrations.py b/tests/test_integrations.py index dfea6d4..7256fb8 100644 --- a/tests/test_integrations.py +++ b/tests/test_integrations.py @@ -23,6 +23,7 @@ uninstall_integration, ) from dyro.integrations import manager +from dyro.read_limits import canonical_entry_path def _record_protocol_section(skill: str) -> str: @@ -59,7 +60,8 @@ def _has_test_verdict_polarity(plain: str) -> bool: class IntegrationManagerTests(unittest.TestCase): def setUp(self) -> None: self.tmp = tempfile.TemporaryDirectory(prefix="dyro-integrations-") - self.root = Path(self.tmp.name) + # Match registry_home()/_dyro_home() which rewrite macOS /var → /private/var. + self.root = canonical_entry_path(Path(self.tmp.name)) self.codex_home = self.root / "codex" self.claude_home = self.root / "claude" self.dyro_home = self.root / "dyro" @@ -1535,5 +1537,134 @@ def test_present_opencode_and_hermes_default_homes_receive_avatars(self) -> None self.assertFalse(hermes_avatar.exists() or hermes_avatar.is_symlink()) +_MACOS_TMP_ALIAS = ( + Path("/tmp").is_symlink() and Path("/tmp").resolve() == Path("/private/tmp") +) + + +class MacOSTmpAliasIntegrationTests(unittest.TestCase): + @unittest.skipUnless(_MACOS_TMP_ALIAS, "requires the macOS /tmp system alias") + def test_manifest_mirror_tmp_alias_spelling_is_not_stale(self) -> None: + with tempfile.TemporaryDirectory(prefix="dyro-int-alias-", dir="/tmp") as temporary: + canonical_home = Path(temporary).resolve() + try: + alias_home = Path("/tmp") / canonical_home.relative_to("/private/tmp") + except ValueError: + self.skipTest("temporary directory is not below /private/tmp") + + codex_home = canonical_home / "codex" + fake_home = canonical_home / "home" + codex_home.mkdir() + fake_home.mkdir() + isolated_hosts = { + spec.env_var: "" for spec in manager.HOSTS if spec.env_var + } + env = { + **isolated_hosts, + "CODEX_HOME": str(codex_home), + "HOME": str(fake_home), + "DYRO_NO_UPDATE_CHECK": "1", + } + with patch.dict(os.environ, {**env, "DYRO_HOME": str(canonical_home)}): + installed = install_integration("skill", yes=True) + self.assertEqual(installed.status.state, IntegrationState.CURRENT) + manifest_path = canonical_home / "integrations" / "skill.json" + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + private_mirror = Path(payload["mirror"]) + alias_mirror = Path("/tmp") / private_mirror.relative_to("/private/tmp") + payload["mirror"] = str(alias_mirror) + for meta in payload["avatars"].values(): + private_avatar = Path(meta["path"]) + meta["path"] = str( + Path("/tmp") / private_avatar.relative_to("/private/tmp") + ) + manifest_path.write_text( + json.dumps(payload, ensure_ascii=True, indent=2, sort_keys=True) + + "\n", + encoding="utf-8", + ) + + with patch.dict(os.environ, {**env, "DYRO_HOME": str(alias_home)}): + status = integration_status("skill") + self.assertEqual(status.state, IntegrationState.CURRENT) + self.assertNotEqual(status.state, IntegrationState.STALE_MANIFEST) + + @unittest.skipUnless(_MACOS_TMP_ALIAS, "requires the macOS /tmp system alias") + def test_avatar_record_tmp_alias_spelling_still_matches(self) -> None: + with tempfile.TemporaryDirectory(prefix="dyro-avatar-alias-", dir="/tmp") as temporary: + canonical = Path(temporary).resolve() + try: + alias = Path("/tmp") / canonical.relative_to("/private/tmp") + except ValueError: + self.skipTest("temporary directory is not below /private/tmp") + avatar = canonical / "skills" / "dyro-control-plane" + avatar.mkdir(parents=True) + recorded = {"path": str(alias / "skills" / "dyro-control-plane"), "kind": "symlink"} + status = manager._inspect_avatar( + host="codex", + avatar=avatar, + mirror=canonical / "mirror", + host_home=canonical, + recorded=recorded, + ) + self.assertEqual(status.state, "drifted") + + @unittest.skipUnless(_MACOS_TMP_ALIAS, "requires the macOS /tmp system alias") + def test_legacy_manifest_tmp_alias_target_is_recognized(self) -> None: + with tempfile.TemporaryDirectory(prefix="dyro-legacy-alias-", dir="/tmp") as temporary: + canonical = Path(temporary).resolve() + try: + alias = Path("/tmp") / canonical.relative_to("/private/tmp") + except ValueError: + self.skipTest("temporary directory is not below /private/tmp") + + codex_home = canonical / "codex" + fake_home = canonical / "home" + dyro_home = canonical / "dyro" + codex_home.mkdir() + fake_home.mkdir() + avatar = codex_home / "skills" / "dyro-control-plane" + avatar.mkdir(parents=True) + files = manager._asset_inventory() + for relative in files: + destination = avatar / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes((manager._asset_root() / relative).read_bytes()) + + alias_avatar = alias / "codex" / "skills" / "dyro-control-plane" + legacy = { + "schema_version": 1, + "integration": "codex", + "asset_version": manager.ASSET_VERSION, + "asset_digest": manager._asset_digest(files), + "target": str(alias_avatar), + "files": files, + } + legacy_manifest = dyro_home / "integrations" / "codex.json" + legacy_manifest.parent.mkdir(parents=True, exist_ok=True) + legacy_manifest.write_text( + json.dumps(legacy, ensure_ascii=True, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + + isolated_hosts = { + spec.env_var: "" for spec in manager.HOSTS if spec.env_var + } + env = { + **isolated_hosts, + "CODEX_HOME": str(codex_home), + "DYRO_HOME": str(dyro_home), + "HOME": str(fake_home), + "DYRO_NO_UPDATE_CHECK": "1", + } + with patch.dict(os.environ, env): + status = integration_status("skill") + self.assertEqual(status.state, IntegrationState.OUTDATED) + migrated = install_integration("skill", yes=True) + self.assertEqual(migrated.status.state, IntegrationState.CURRENT) + self.assertTrue(avatar.is_symlink()) + self.assertFalse(legacy_manifest.exists()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_state.py b/tests/test_state.py index 704d746..8d90d02 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -5,6 +5,10 @@ from dyro.errors import DyroError from dyro.state import atomic_write_text, ensure_safe_child_directory, exclusive_directory_lock, exclusive_lock +_MACOS_TMP_ALIAS = ( + Path("/tmp").is_symlink() and Path("/tmp").resolve() == Path("/private/tmp") +) + class StateTests(unittest.TestCase): def test_atomic_write_and_reentrant_lock_leave_complete_state(self) -> None: @@ -37,3 +41,18 @@ def test_descriptor_scoped_directory_lock_and_create_reject_symlink_parent(self) self.assertFalse((outside / "objectives").exists()) self.assertFalse((outside / "objectives.lock").exists()) + + @unittest.skipUnless(_MACOS_TMP_ALIAS, "requires the macOS /tmp system alias") + def test_exclusive_lock_reentry_across_tmp_alias_spellings(self) -> None: + with tempfile.TemporaryDirectory(prefix="dyro-lock-alias-", dir="/tmp") as temporary: + canonical = Path(temporary).resolve() + try: + alias = Path("/tmp") / canonical.relative_to("/private/tmp") + except ValueError: + self.skipTest("temporary directory is not below /private/tmp") + lock_canonical = canonical / "state.lock" + lock_alias = alias / "state.lock" + with exclusive_lock(lock_canonical, timeout_seconds=0.2): + with exclusive_lock(lock_alias, timeout_seconds=0.2): + atomic_write_text(canonical / "value", "ok\n") + self.assertEqual((canonical / "value").read_text(encoding="utf-8"), "ok\n")