"""muse attributes — query and display ``.museattributes`` merge-strategy rules. Reads, validates, and pretty-prints the ``.museattributes`` file from the current repository. Supports tabular display, path-strategy resolution, and file validation via three subcommands. Subcommands ----------- ``muse attributes list`` Pretty-print all rules in a table showing path pattern, dimension, strategy, priority, and comment. This is the **default** when no subcommand is given. ``muse attributes check PATH [PATH ...]`` Resolve the merge strategy for one or more workspace-relative paths, optionally filtered by dimension. ``muse attributes validate`` Validate the ``.museattributes`` file for TOML syntax errors, missing required fields, and unknown strategy values. Security model -------------- - All user-controlled values read from ``.museattributes`` (domain, path patterns, dimensions, strategies, comments) are passed through ``sanitize_display()`` before appearing in human-readable output. - TOML parse errors and strategy validation errors are reported to **stderr** without printing a raw traceback. - ``_parse_raw`` enforces a 1 MiB file-size cap, preventing OOM from a crafted or corrupted file. - Null bytes in paths supplied to ``check`` are rejected with a clear error. Agent UX -------- Every subcommand accepts ``--json`` for machine-readable output on **stdout**. All diagnostic and error messages go to **stderr** so that JSON consumers never see noise on stdout. JSON schemas ------------ ``muse attributes list --json``:: { "domain": "midi", // always present; empty string when unset "rules": [ { "path_pattern": "drums/*", "dimension": "*", "strategy": "ours", "comment": "Drums are always authored by branch A.", "priority": 10, "source_index": 0 } ] } ``muse attributes check --json``:: { "results": [ { "path": "drums/kick.mid", "dimension": "*", "strategy": "ours", "rule_index": 0 } ] } ``muse attributes validate --json``:: { "valid": true, "errors": [] } Exit codes ---------- - 0 — success - 1 — user error (bad args, invalid strategy, TOML parse error, invalid path) - 2 — not inside a Muse repository """ from __future__ import annotations import argparse import fnmatch import json import sys from typing import TYPE_CHECKING, TypedDict from muse.core.attributes import ( AttributeRule, AttributesMeta, load_attributes_full, ) from muse.core.errors import ExitCode from muse.core.repo import require_repo from muse.core.validation import sanitize_display # --------------------------------------------------------------------------- # JSON TypedDicts — stable, machine-readable output schemas # --------------------------------------------------------------------------- class _RuleJson(TypedDict): """JSON representation of a single ``.museattributes`` rule.""" path_pattern: str dimension: str strategy: str comment: str priority: int source_index: int class _ListJson(TypedDict): """JSON output of ``muse attributes list``.""" domain: str rules: list[_RuleJson] class _CheckResultJson(TypedDict): """JSON result for a single path resolution.""" path: str dimension: str strategy: str rule_index: int # -1 when no rule matched (default "auto") class _CheckJson(TypedDict): """JSON output of ``muse attributes check``.""" results: list[_CheckResultJson] class _ValidateErrorJson(TypedDict): """A single validation error entry.""" kind: str # "syntax" | "semantic" | "missing" message: str class _ValidateJson(TypedDict): """JSON output of ``muse attributes validate``.""" valid: bool errors: list[_ValidateErrorJson] # --------------------------------------------------------------------------- # Internal helpers # --------------------------------------------------------------------------- def _resolve_with_index( rules: list[AttributeRule], path: str, dimension: str, ) -> tuple[str, int]: """Return ``(strategy, rule.source_index)`` for *path* / *dimension*. Implements the same first-match semantics as :func:`resolve_strategy` but also returns which rule was matched so callers can explain the decision. Returns ``("auto", -1)`` when no rule matches. Args: rules: Priority-sorted rule list from :func:`load_attributes_full`. path: Workspace-relative POSIX path. dimension: Domain axis name or ``"*"`` to match any dimension. """ for rule in rules: path_match = fnmatch.fnmatch(path, rule.path_pattern) dim_match = ( rule.dimension == "*" or rule.dimension == dimension or dimension == "*" ) if path_match and dim_match: return rule.strategy, rule.source_index return "auto", -1 def _rule_to_json(rule: AttributeRule) -> _RuleJson: """Convert an :class:`AttributeRule` to its JSON TypedDict form.""" return _RuleJson( path_pattern=rule.path_pattern, dimension=rule.dimension, strategy=rule.strategy, comment=rule.comment, priority=rule.priority, source_index=rule.source_index, ) # --------------------------------------------------------------------------- # Command registration # --------------------------------------------------------------------------- def register( subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]", ) -> None: """Register the ``attributes`` subcommand tree and all its flags. Every subcommand accepts ``--json`` for machine-readable output on stdout. All diagnostic messages go to stderr. """ parser = subparsers.add_parser( "attributes", help="Query and display .museattributes merge-strategy rules.", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) subs = parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND") subs.required = True # ── check ───────────────────────────────────────────────────────────── check_p = subs.add_parser( "check", help="Resolve the merge strategy for one or more workspace-relative paths.", description=( "Apply ``.museattributes`` rule matching to one or more paths and\n" "print the resolved strategy for each. Uses first-match semantics:\n" "rules are evaluated in descending priority order; the first rule\n" "whose path glob and dimension both match wins.\n\n" "``rule_index`` in the output identifies which ``[[rules]]`` entry\n" "matched (0-based source order); ``-1`` means no rule matched and\n" "the default ``auto`` strategy applies. Use ``-d`` / ``--dimension``\n" "to filter by a specific domain axis.\n\n" "Agent quickstart\n" "----------------\n" " muse attributes check src/foo.py --json\n" " muse attributes check src/foo.py -j\n" " muse attributes check a.mid b.mid -d pitch_bend --json\n" " muse attributes check src/*.py --json | jq '.results[] | select(.strategy!=\"auto\")'\n\n" "JSON output schema\n" "------------------\n" ' {"results": [{"path": "", "dimension": "",\n' ' "strategy": "", "rule_index": }, ...]}\n\n' "Exit codes\n" "----------\n" " 0 — all paths resolved (no-match defaults are still success)\n" " 1 — null byte in a path arg, TOML parse error, or unknown strategy\n" " 2 — not inside a Muse repository\n" ), formatter_class=argparse.RawDescriptionHelpFormatter, ) check_p.add_argument( "paths", nargs="+", metavar="PATH", help="Workspace-relative path(s) to resolve.", ) check_p.add_argument( "--dimension", "-d", default="*", metavar="DIM", help="Domain dimension to match against (default: '*' matches any).", ) check_p.add_argument( "--json", "-j", action="store_true", dest="output_json", default=False, help="Emit a JSON object with a 'results' array to stdout.", ) check_p.set_defaults(func=run_check) # ── list ────────────────────────────────────────────────────────────── list_p = subs.add_parser( "list", help="Pretty-print all rules (path pattern, dimension, strategy, priority, comment).", description=( "Parse ``.museattributes`` and display every rule as an aligned\n" "table showing path pattern, dimension, strategy, priority, and\n" "comment. An optional priority column appears only when at least\n" "one rule has a non-zero priority. A comment column appears only\n" "when at least one rule carries a comment.\n\n" "Agent quickstart\n" "----------------\n" " muse attributes list --json\n" " muse attributes list -j\n" " DOMAIN=$(muse attributes list --json | jq -r .domain)\n" " muse attributes list --json | jq '.rules[] | select(.strategy==\"ours\")'\n\n" "JSON output schema\n" "------------------\n" ' {"domain": "",\n' ' "rules": [{"path_pattern": "", "dimension": "",\n' ' "strategy": "", "comment": "",\n' ' "priority": , "source_index": }, ...]}\n\n' "Exit codes\n" "----------\n" " 0 — success (empty rules list is still success)\n" " 1 — TOML parse error or unknown strategy\n" " 2 — not inside a Muse repository\n" ), formatter_class=argparse.RawDescriptionHelpFormatter, ) list_p.add_argument( "--json", "-j", action="store_true", dest="output_json", default=False, help="Emit a JSON object to stdout with domain and rules array.", ) list_p.set_defaults(func=run_list) # ── validate ────────────────────────────────────────────────────────── validate_p = subs.add_parser( "validate", help="Validate .museattributes for TOML syntax and semantic correctness.", description=( "Parse ``.museattributes`` and check for TOML syntax errors,\n" "missing required rule fields, unknown strategy values, and the\n" "1 MiB file-size limit. Exits 0 only when the file is fully\n" "valid; exits 1 for any validation failure.\n\n" "In text mode, prints a one-line summary with the rule count and\n" "domain on success, or an error message on failure.\n\n" "Agent quickstart\n" "----------------\n" " muse attributes validate --json\n" " muse attributes validate -j\n" " muse attributes validate --json | jq .valid\n" " muse attributes validate --json | jq '.errors[].kind'\n\n" "JSON output schema\n" "------------------\n" ' {"valid": ,\n' ' "errors": [{"kind": "missing"|"syntax"|"semantic",\n' ' "message": ""}, ...]}\n\n' "Error kinds\n" "-----------\n" ' "missing" — .museattributes does not exist\n' ' "semantic" — TOML parsed but a rule field is invalid\n\n' "Exit codes\n" "----------\n" " 0 — file is valid\n" " 1 — file is missing, malformed, or contains unknown strategies\n" " 2 — not inside a Muse repository\n" ), formatter_class=argparse.RawDescriptionHelpFormatter, ) validate_p.add_argument( "--json", "-j", action="store_true", dest="output_json", default=False, help="Emit a JSON object with 'valid' and 'errors' fields to stdout.", ) validate_p.set_defaults(func=run_validate) # --------------------------------------------------------------------------- # Subcommand handlers # --------------------------------------------------------------------------- def run_list(args: argparse.Namespace) -> None: """Display all ``.museattributes`` rules in tabular or JSON format. Parses the file in a single pass (meta + rules together), sanitizes all user-controlled values before output, and routes every diagnostic to stderr so that stdout carries only data. Security: ``domain``, ``path_pattern``, ``dimension``, ``strategy``, and ``comment`` are all passed through ``sanitize_display()`` in text mode. Raw values are preserved verbatim in JSON output. JSON output fields (``--json`` / ``-j``) ----------------------------------------- ``domain`` Repository domain string from the ``[meta]`` section; empty string when the ``[meta]`` section is absent or ``domain`` is unset. ``rules`` Array of rule objects, sorted by descending priority (highest first), then by ascending ``source_index`` for stable ordering within a priority tier. Each rule object contains: ``path_pattern`` Glob pattern matched against workspace-relative POSIX paths. ``dimension`` Domain axis name, or ``"*"`` to match any dimension. ``strategy`` Merge strategy string (e.g. ``"ours"``, ``"theirs"``, ``"auto"``). ``comment`` Optional free-text annotation from the ``.museattributes`` file. ``priority`` Integer priority; higher values take precedence. ``source_index`` Zero-based position of the rule in the file, used for deterministic tie-breaking and for ``muse attributes check`` cross-references. Exit codes ---------- 0 — success (empty rules list is still success) 1 — TOML parse error or unknown strategy in ``.museattributes`` 2 — not inside a Muse repository """ output_json: bool = args.output_json root = require_repo() try: meta, rules = load_attributes_full(root) except ValueError as exc: print(f"❌ {exc}", file=sys.stderr) raise SystemExit(ExitCode.USER_ERROR.value) from exc domain_raw: str = meta.get("domain") or "" if output_json: payload: _ListJson = { "domain": domain_raw, "rules": [_rule_to_json(r) for r in rules], } print(json.dumps(payload)) return if not rules: attr_file = root / ".museattributes" if not attr_file.exists(): print( "No .museattributes file found.", file=sys.stderr, ) else: print( ".museattributes is present but contains no rules.", file=sys.stderr, ) print( "Create one at the repository root to declare per-path merge strategies.", file=sys.stderr, ) return if domain_raw: print(f"Domain: {sanitize_display(domain_raw)}") print() has_comments = any(r.comment for r in rules) has_nonzero_priority = any(r.priority != 0 for r in rules) pat_w = max(len("Path pattern"), max(len(r.path_pattern) for r in rules)) dim_w = max(len("Dimension"), max(len(r.dimension) for r in rules)) pri_w = max(len("Pri"), max(len(str(r.priority)) for r in rules)) header_parts = [ f"{'Path pattern':<{pat_w}}", f"{'Dimension':<{dim_w}}", f"{'Pri':>{pri_w}}", "Strategy", ] sep_parts = ["-" * pat_w, "-" * dim_w, "-" * pri_w, "--------"] if has_comments: header_parts.append("Comment") sep_parts.append("-------") print(" ".join(header_parts)) print(" ".join(sep_parts)) for rule in rules: pat = sanitize_display(rule.path_pattern) dim = sanitize_display(rule.dimension) strat = sanitize_display(rule.strategy) pri_str = str(rule.priority) if has_nonzero_priority else "" line_parts = [ f"{pat:<{pat_w}}", f"{dim:<{dim_w}}", f"{pri_str:>{pri_w}}", strat, ] if has_comments: comment = sanitize_display(rule.comment) line_parts.append(comment) print(" ".join(line_parts)) def run_check(args: argparse.Namespace) -> None: """Resolve the merge strategy for each given path. Uses the same first-match rule semantics as the merge engine. Returns the matched rule's ``source_index`` (0-based declaration order) so agents can correlate results back to the original ``[[rules]]`` entries. A ``rule_index`` of ``-1`` means the default ``"auto"`` strategy applied. Security: null bytes in caller-supplied paths are rejected with a clear USER_ERROR before any rule resolution occurs. In text mode, paths and strategy strings are passed through ``sanitize_display()`` before output to strip ANSI escape sequences and other control characters. JSON output fields (``--json`` / ``-j``) ----------------------------------------- ``results`` Array of one result object per input path, in the same order as the arguments supplied on the command line. Each result contains: ``path`` The input path string, preserved verbatim (not sanitized). ``dimension`` The dimension string used for resolution (echoed from ``-d`` / ``--dimension``; defaults to ``"*"`` which matches any). ``strategy`` Resolved merge strategy, e.g. ``"ours"``, ``"theirs"``, ``"auto"``. Always ``"auto"`` when no rule matched. ``rule_index`` 0-based ``source_index`` of the matched rule in ``.museattributes``. ``-1`` when no rule matched (default ``"auto"`` strategy applied). Exit codes ---------- 0 — all paths resolved (including no-match defaults) 1 — null byte in a path arg, TOML parse error, or unknown strategy 2 — not inside a Muse repository """ output_json: bool = args.output_json paths: list[str] = args.paths dimension: str = args.dimension root = require_repo() try: _, rules = load_attributes_full(root) except ValueError as exc: print(f"❌ {exc}", file=sys.stderr) raise SystemExit(ExitCode.USER_ERROR.value) from exc results: list[_CheckResultJson] = [] for raw_path in paths: if "\x00" in raw_path: print(f"❌ null byte in path: {raw_path!r}", file=sys.stderr) raise SystemExit(ExitCode.USER_ERROR.value) strategy, rule_idx = _resolve_with_index(rules, raw_path, dimension) results.append( _CheckResultJson( path=raw_path, dimension=dimension, strategy=strategy, rule_index=rule_idx, ) ) if output_json: payload: _CheckJson = {"results": results} print(json.dumps(payload)) return for item in results: path_disp = sanitize_display(item["path"]) strat_disp = sanitize_display(item["strategy"]) if item["rule_index"] >= 0: rule_note = f" (rule #{item['rule_index']})" else: rule_note = " (default)" print(f"{path_disp}: {strat_disp}{rule_note}") def run_validate(args: argparse.Namespace) -> None: """Validate ``.museattributes`` for syntax and semantic correctness. Checks performed (in order): - File exists at the repository root. - TOML is syntactically valid and within the 1 MiB size limit. - All ``[[rules]]`` entries have the required fields (``path``, ``dimension``, ``strategy``). - Every ``strategy`` value is one of the recognised strategies (``"auto"``, ``"ours"``, ``"theirs"``, ``"union"``, ``"manual"``, ``"custom"``). Exits 0 when the file is fully valid; exits ``USER_ERROR`` (1) on any validation failure. Security: error messages written to stderr come from ``load_attributes_full`` and may include fragments of the ``strategy`` value from the file. They are written to stderr only, never stdout. In text mode, the domain string in the success message is passed through ``sanitize_display()`` before output. JSON output fields (``--json`` / ``-j``) ----------------------------------------- ``valid`` ``true`` when the file passes all checks; ``false`` otherwise. ``errors`` Array of error objects (empty on success). Each error has: ``kind`` ``"missing"`` — file does not exist. ``"semantic"`` — TOML parsed but a rule field is invalid (bad strategy, missing required field, or size exceeded). ``message`` Human-readable description of the specific error. Exit codes ---------- 0 — file is valid 1 — file is missing, malformed, or contains unknown strategies 2 — not inside a Muse repository """ output_json: bool = args.output_json root = require_repo() attr_file = root / ".museattributes" errors: list[_ValidateErrorJson] = [] if not attr_file.exists(): errors.append( _ValidateErrorJson( kind="missing", message=".museattributes file does not exist", ) ) if output_json: payload: _ValidateJson = {"valid": False, "errors": errors} print(json.dumps(payload)) else: print("❌ .museattributes file does not exist.", file=sys.stderr) raise SystemExit(ExitCode.USER_ERROR.value) try: meta, rules = load_attributes_full(root) except ValueError as exc: errors.append(_ValidateErrorJson(kind="semantic", message=str(exc))) if output_json: payload = {"valid": False, "errors": errors} print(json.dumps(payload)) else: print(f"❌ {errors[0]['message']}", file=sys.stderr) raise SystemExit(ExitCode.USER_ERROR.value) from exc if output_json: payload = {"valid": True, "errors": []} print(json.dumps(payload)) return domain_raw = meta.get("domain") or "" domain_disp = sanitize_display(domain_raw) if domain_raw else "(not set)" print( f"✅ .museattributes is valid — {len(rules)} rule(s), " f"domain: {domain_disp}" )