"""Canonical path helpers for the Muse on-disk layout. Every place in the codebase that constructs a path inside ``.muse/`` (or the user-global ``~/.muse/``) must call one of these helpers. Inline path construction — ``root / ".muse" / "refs" / "heads"`` — is banned; it duplicates the layout knowledge and makes future restructuring impossible. All repo-local helpers take ``root: pathlib.Path`` (the repository root, i.e. the directory containing ``.muse/``). All user-global helpers take no arguments and derive their base from ``pathlib.Path.home()``. Composability rule: every helper calls a lower-level helper rather than reconstructing path segments from scratch. ``ref_path`` calls ``heads_dir``; ``heads_dir`` calls ``refs_dir``; ``refs_dir`` calls ``muse_dir``. Adding a new layout concept means choosing the right parent helper to compose from. """ import pathlib from muse.core.types import MUSE_DIR, OBJECTS_DIR # --------------------------------------------------------------------------- # Repo-local helpers (all take root: pathlib.Path) # --------------------------------------------------------------------------- def muse_dir(root: pathlib.Path) -> pathlib.Path: """Return the ``.muse/`` directory for the repository at *root*.""" return root / MUSE_DIR def objects_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/objects/`` — the content-addressed object store.""" return muse_dir(root) / OBJECTS_DIR def packs_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/objects/pack/sha256/`` — the MPack local store. Algorithm is canonical in the path, mirroring the loose object layout (``.muse/objects/sha256//``). Pack files are stored as ``/<64hex>.mpack`` and indexed at ``/<64hex>.idx``. """ from muse.core.types import DEFAULT_HASH_ALGO return objects_dir(root) / "pack" / DEFAULT_HASH_ALGO def commits_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/commits/``.""" return muse_dir(root) / "commits" def snapshots_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/snapshots/``.""" return muse_dir(root) / "snapshots" def tags_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/tags/``.""" return muse_dir(root) / "tags" def releases_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/releases/``.""" return muse_dir(root) / "releases" def indices_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/indices/``.""" return muse_dir(root) / "indices" def coordination_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/coordination/``.""" return muse_dir(root) / "coordination" def harmony_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/harmony/``.""" return muse_dir(root) / "harmony" def logs_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/logs/``.""" return muse_dir(root) / "logs" def symlogs_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/symlogs/`` — root of the per-symbol live journal.""" return muse_dir(root) / "symlogs" def refs_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/refs/``.""" return muse_dir(root) / "refs" def heads_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/refs/heads/``.""" return refs_dir(root) / "heads" def remotes_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/remotes/`` — remote tracking ref root.""" return muse_dir(root) / "remotes" def remote_tracking_dir(root: pathlib.Path, remote: str) -> pathlib.Path: """Return ``.muse/remotes//`` — tracking refs for one remote.""" return remotes_dir(root) / remote def ref_path(root: pathlib.Path, branch: str) -> pathlib.Path: """Return the ref file path for *branch* under ``.muse/refs/heads/``.""" return heads_dir(root) / branch def remote_ref_path(root: pathlib.Path, remote: str, branch: str) -> pathlib.Path: """Return the ref file path for *branch* under ``.muse/remotes//``.""" return remotes_dir(root) / remote / branch def head_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/HEAD``.""" return muse_dir(root) / "HEAD" def repo_json_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/repo.json``.""" return muse_dir(root) / "repo.json" def config_toml_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/config.toml``.""" return muse_dir(root) / "config.toml" def workspace_toml_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/workspace.toml``.""" return muse_dir(root) / "workspace.toml" def shelf_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/shelf/`` — root of the per-entry shelf layout. Shelf entries are stored as ``.muse/shelf//`` (no extension), using git-object-style framing (``shelf \\0``). The algo segment is derived from each entry's content-addressed ID prefix (e.g. ``sha256``), making the layout forward-compatible with future hash algorithms. This helper is the single source of truth for the shelf directory location. Never construct ``.muse/shelf`` inline — call this helper. """ return muse_dir(root) / "shelf" def shelf_json_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/shelf.json``. .. deprecated:: Retained only for GC migration detection. New code must use :func:`shelf_dir` and the per-entry git-header+JSON layout. """ return muse_dir(root) / "shelf.json" def agent_md_path(root: pathlib.Path) -> pathlib.Path: """Return ``.museagent.md`` — the canonical agent-config source. Deliberately lives at the repo/workspace root, not inside ``.muse/`` — ``.muse/`` is unconditionally excluded from every snapshot (``_ALWAYS_IGNORE_DIRS``), so a file placed there could never be tracked, defeating agent-config's entire "clone, sync, get your tool's adapter" promise. See muse issue #78. """ return root / ".museagent.md" def hooks_installed_toml_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/hooks-installed.toml`` — local-only hook activation state. Deliberately local, unlike :func:`agent_md_path`'s ``.museagent.md``: whether *this specific clone* has run ``muse hooks install`` is not meant to be shared — a cloned repo must never auto-activate hooks (see ``muse/core/hooks.py`` and musehub#192). Living inside ``.muse/`` is the *correct* choice here, since ``.muse/`` is unconditionally excluded from every snapshot and this state should never propagate. """ return muse_dir(root) / "hooks-installed.toml" def shallow_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/shallow``.""" return muse_dir(root) / "shallow" def bisect_state_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/BISECT_STATE.toml``.""" return muse_dir(root) / "BISECT_STATE.toml" def merge_state_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/MERGE_STATE.json``.""" return muse_dir(root) / "MERGE_STATE.json" def stability_toml_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/stability.toml``.""" return muse_dir(root) / "stability.toml" def cache_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/`` — all recomputable JSON cache files live here.""" return muse_dir(root) / "cache" def stat_cache_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/stat.json``.""" return cache_dir(root) / "stat.json" def symbol_cache_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/symbols.json``.""" return cache_dir(root) / "symbols.json" def callgraph_cache_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/callgraph.json``.""" return cache_dir(root) / "callgraph.json" def implicit_edge_cache_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/implicit_edges.json``.""" return cache_dir(root) / "implicit_edges.json" def invariants_cache_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/invariants.json``.""" return cache_dir(root) / "invariants.json" def midi_invariants_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/midi_invariants.toml``.""" return muse_dir(root) / "midi_invariants.toml" def rebase_merge_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/rebase-merge/`` — in-progress rebase state directory.""" return muse_dir(root) / "rebase-merge" def test_history_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/cache/test_history.json``.""" return cache_dir(root) / "test_history.json" def maintenance_json_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/maintenance.json``.""" return muse_dir(root) / "maintenance.json" def reflog_heads_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/logs/refs/heads/`` — reflog directory for local branches.""" return logs_dir(root) / "refs" / "heads" def reflog_branch_path(root: pathlib.Path, branch: str) -> pathlib.Path: """Return the reflog file for *branch* under ``.muse/logs/refs/heads/``.""" return reflog_heads_dir(root) / branch def prev_branch_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/PREV_BRANCH`` — stores the previous branch for ``switch -``.""" return muse_dir(root) / "PREV_BRANCH" def checkout_head_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/CHECKOUT_HEAD`` — sentinel written during in-progress checkouts.""" return muse_dir(root) / "CHECKOUT_HEAD" def code_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/code/`` — code-domain working files.""" return muse_dir(root) / "code" def code_stage_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/code/stage.json``.""" return code_dir(root) / "stage.json" def code_config_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/code_config.toml``.""" return muse_dir(root) / "code_config.toml" def code_manifests_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/code_manifests/``.""" return muse_dir(root) / "code_manifests" def sparse_checkout_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/sparse-checkout``.""" return muse_dir(root) / "sparse-checkout" def dead_allowlist_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/dead-allowlist.json``.""" return muse_dir(root) / "dead-allowlist.json" def ci_toml_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/ci.toml``.""" return muse_dir(root) / "ci.toml" def docs_toml_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/docs.toml``.""" return muse_dir(root) / "docs.toml" def op_log_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/op_log/``.""" return muse_dir(root) / "op_log" def rebase_state_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/REBASE_STATE.json``.""" return muse_dir(root) / "REBASE_STATE.json" def worktrees_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/worktrees/``.""" return muse_dir(root) / "worktrees" def code_invariants_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/code_invariants.toml``.""" return muse_dir(root) / "code_invariants.toml" def entity_index_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/entity_index/``.""" return muse_dir(root) / "entity_index" def music_manifests_dir(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/music_manifests/``.""" return muse_dir(root) / "music_manifests" def git_bridge_state_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/git-bridge.toml``.""" return muse_dir(root) / "git-bridge.toml" def git_bridge_sidecar_path(root: pathlib.Path) -> pathlib.Path: """Return ``.muse/git-bridge-p8.json``.""" return muse_dir(root) / "git-bridge-p8.json" # --------------------------------------------------------------------------- # User-global helpers (no root argument — based on ~/.muse/) # --------------------------------------------------------------------------- def user_muse_dir() -> pathlib.Path: """Return ``~/.muse/`` — the user-global Muse directory.""" return pathlib.Path.home() / MUSE_DIR def user_keys_dir() -> pathlib.Path: """Return ``~/.muse/keys/``.""" return user_muse_dir() / "keys" def user_hub_trust_path() -> pathlib.Path: """Return ``~/.muse/hub_trust.toml``.""" return user_muse_dir() / "hub_trust.toml" def user_agent_slots_path() -> pathlib.Path: """Return ``~/.muse/agent-slots.toml``.""" return user_muse_dir() / "agent-slots.toml" def user_config_toml_path() -> pathlib.Path: """Return ``~/.muse/config.toml`` — user-global config (safe_dirs, etc.).""" return user_muse_dir() / "config.toml" def user_identity_toml_path() -> pathlib.Path: """Return ``~/.muse/identity.toml``.""" return user_muse_dir() / "identity.toml" def user_domain_registry_path() -> pathlib.Path: """Return ``~/.muse/domain-registry.json``.""" return user_muse_dir() / "domain-registry.json" # --------------------------------------------------------------------------- # Server-side per-repo store helpers (MuseHub / remote server) # --------------------------------------------------------------------------- def server_repo_root(repos_dir: pathlib.Path, owner: str, slug: str) -> pathlib.Path: """Return the canonical on-disk root for a server-side repo. Layout: ``///`` This mirrors the local ``.muse/`` layout convention — the *repo root* is the directory that directly contains the ``objects/``, ``refs/``, and ``HEAD`` subdirectories. All server-side path helpers take the value returned here as their ``repo_root`` argument. Path traversal via *owner* or *slug* is rejected; both components must resolve to a path strictly inside *repos_dir*. Args: repos_dir: Base directory for all server-side repos (e.g. ``/data/repos``). owner: Repository owner handle. slug: Repository slug. Returns: Absolute, unresolved path ``repos_dir / owner / slug``. Raises: ValueError: If the resolved path would escape *repos_dir*. """ base = repos_dir.resolve() candidate = (repos_dir / owner / slug).resolve() if not str(candidate).startswith(f"{base}/") and candidate != base: raise ValueError( f"Path traversal detected: owner={owner!r} slug={slug!r} " f"escapes repos_dir={repos_dir!r}" ) return candidate def server_objects_dir(repo_root: pathlib.Path) -> pathlib.Path: """Return the object store directory for a server-side repo. Layout: ``/objects/`` Mirrors :func:`objects_dir` for local repos (which returns ``/.muse/objects/``). The server omits the ``.muse/`` wrapper because repos are bare — there is no working tree. """ return repo_root / OBJECTS_DIR def server_refs_dir(repo_root: pathlib.Path) -> pathlib.Path: """Return ``/refs/`` for a server-side repo.""" return repo_root / "refs" def server_heads_dir(repo_root: pathlib.Path) -> pathlib.Path: """Return ``/refs/heads/`` for a server-side repo.""" return server_refs_dir(repo_root) / "heads" def server_ref_path(repo_root: pathlib.Path, branch: str) -> pathlib.Path: """Return the ref file path for *branch* in a server-side repo. Layout: ``/refs/heads/`` """ return server_heads_dir(repo_root) / branch def server_head_path(repo_root: pathlib.Path) -> pathlib.Path: """Return ``/HEAD`` for a server-side repo.""" return repo_root / "HEAD" def server_object_path( repo_root: pathlib.Path, object_id: str, prefix_len: int = 2, ) -> pathlib.Path: """Return the canonical on-disk path for an object in a server-side bare repo. Server-side repos are bare — there is no working tree or ``.muse/`` wrapper. Objects are stored directly under ``/objects/``: ``/objects///`` This mirrors the local ``object_path`` layout (``/.muse/objects/…``) in every respect *except* the leading ``.muse/`` — both use algo-namespaced + N-char sharding so objects can be hardlinked or transferred between the two layouts without re-hashing. Args: repo_root: Root of the server-side bare repo (e.g. ``/data/repos/alice/muse``). object_id: Prefixed SHA-256 object ID (``sha256:<64hex>``). prefix_len: Shard prefix length (default ``2``). Returns: Absolute path to the object file (may not yet exist). Raises: ValueError: If *object_id* is not a valid prefixed SHA-256 object ID. """ from muse.core.types import DEFAULT_HASH_ALGO, split_id from muse.core.validation import validate_object_id validate_object_id(object_id) _, hex_id = split_id(object_id) return server_objects_dir(repo_root) / DEFAULT_HASH_ALGO / hex_id[:prefix_len] / hex_id[prefix_len:] # --------------------------------------------------------------------------- # Repo bootstrapping helper (testing + `muse init` internals) # --------------------------------------------------------------------------- def init_repo_dirs(root: pathlib.Path) -> pathlib.Path: """Create the minimal ``.muse/`` directory tree under *root*. Idempotent — safe to call on a repo that already has some or all of the required directories. Does **not** write ``HEAD``, ``repo.json``, or any other file; callers that need those must write them separately. Use this in tests and in ``muse init`` internals rather than spelling out ``(root / ".muse" / "refs" / "heads").mkdir(parents=True, exist_ok=True)`` inline — that duplicates layout knowledge. Args: root: Repository root directory (the directory that will contain ``.muse/``). Created with ``parents=True`` if it does not exist. Returns: *root* — allows the common ``repo = init_repo_dirs(tmp_path)`` pattern. """ for make_dir in ( muse_dir, objects_dir, heads_dir, remotes_dir, logs_dir, shelf_dir, ): make_dir(root).mkdir(parents=True, exist_ok=True) return root