Metadata-Version: 2.4
Name: mayakit
Version: 0.34.0
Summary: A toolkit for Maya pipeline work. Its scenedoc module turns a Maya scene into a stable, versioned data document.
Author: narutozb
License-Expression: MIT
Project-URL: Homepage, https://github.com/narutozb/mayakit
Project-URL: Repository, https://github.com/narutozb/mayakit
Project-URL: Issues, https://github.com/narutozb/mayakit/issues
Project-URL: Changelog, https://github.com/narutozb/mayakit/blob/main/CHANGELOG.md
Keywords: maya,autodesk,vfx,pipeline,3d,scene,dcc,asset-management
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "dev"
Dynamic: license-file

# mayakit

A toolkit for Maya pipeline work, organised as independent modules under one
package.

| Package | What it is |
|---|---|
| **`mayakit.core`** | The shared framework: the document contract, the `Collector` base class and registry, parameter handling, serialization both ways, the runner, **document comparison** and **rule checking**. Knows nothing about any DCC. |
| **`mayakit.scenedoc`** | Turns a Maya scene — `.ma`, `.mb` or `.fbx` — into a **stable, versioned data document** (JSON) for other tools, frontends and backends to consume. |

The top level is deliberately thin — it holds the package identity and the
module list, nothing else. Each module owns its own public API and its own
collector registry, so adding a second module can never collide with the first
over a name like `scan`, `dumps` or a collector called `meshes`.

The point of `core` being source-agnostic: a scene and an exported file
describe the *same concepts*. A mesh is a mesh, a joint is a joint, a bind pose
is a bind pose. One schema for all sources means one set of tables on the
backend, instead of a separate model per source to reconcile by hand.

This package covers the Maya side only. It contains no web service, database or
UI — but the data it emits is shaped for something that will eventually go into
a database and travel over an API.

[![Python](https://img.shields.io/badge/python-3.9%2B-blue)](https://github.com/narutozb/mayakit)
[![Maya](https://img.shields.io/badge/maya-2023%E2%80%932027-brightgreen)](https://github.com/narutozb/mayakit)
[![License](https://img.shields.io/badge/license-MIT-lightgrey)](LICENSE)

📖 **中文文档：[README.zh-CN.md](README.zh-CN.md)**

---

## Install

> ### What is on PyPI, and what is on `main`
>
> **PyPI currently has `0.3.0`** (uploaded 2026-08-22). `main` is well ahead of
> it, and **this README documents `main`.** If you `pip install mayakit` today
> and follow the sections below, the Diff API, `topology_hash` and the
> diagnostics will not be there — `from mayakit.core.diff import
> diff_documents` raises `ModuleNotFoundError`.
>
> Until the next release, use a source install (`pip install -e .` or
> `pip install git+https://github.com/narutozb/mayakit`) for anything in this
> document, or pin to what `0.3.0` actually provides:
>
> | | on PyPI `0.3.0` | on `main` |
> | --- | --- | --- |
> | `scenedoc.scan_current_scene()`, batch scan | yes | yes |
> | public Diff API (`mayakit.core.diff`) | **no** | yes |
> | `MeshInfo.topology_hash` — a topology edit that keeps the counts | **no** | yes |
> | `open_scene()` passing `executeScriptNodes=False` | **no** | yes |
> | a failed scene reset refusing to read on | **no** | yes |
> | `Diagnostic` / `partial` — a failed read not passing for a measurement | **no** | yes |
> | rules, artifacts, query fingerprints, the 0/1/2/3 exit contract | **no** | yes |
>
> Pin to `mayakit.scenedoc.SCHEMA_VERSION` rather than to the release number —
> the code ships many times without the document shape changing. Reported in
> [#25](https://github.com/narutozb/mayakit/issues/25).

**Zero runtime dependencies**, deliberately: this installs into `mayapy`, where
every extra wheel is a version clash waiting to happen.

Into Maya (swap 2026 for your version):

```bash
"C:/Program Files/Autodesk/Maya2026/bin/mayapy.exe" -m pip install mayakit
```

Or somewhere else, and point `PYTHONPATH` at it, if you would rather not touch
the Maya installation:

```bash
"C:/Program Files/Autodesk/Maya2026/bin/mayapy.exe" -m pip install --target D:/maya_site mayakit
```

From source, for development:

```bash
"C:/Program Files/Autodesk/Maya2026/bin/mayapy.exe" -m pip install -e .
```

It also installs into a plain Python interpreter. Everything except actually
opening a `.ma`/`.mb` file — the schema, the collector logic, reading documents
back, the whole test suite — runs with no Maya at all.

---

## `mayakit.scenedoc`

Everything below describes the `scenedoc` module.

### Why not a class per Maya node type

The obvious design is an inheritance tree that mirrors Maya's concepts:
`SceneBase → Scene → SceneFunctions`, `Property → Vector → DetailProperty`, and
so on. It does not survive contact with a real pipeline:

| Problem | Consequence |
|---|---|
| The tree has to chase Maya's node types | Maya has a thousand of them, each growing attributes at runtime. The base classes are never finished. |
| Base classes both *store data* and *query Maya* | `maya.cmds` ends up imported at every level, so nothing can be imported or tested outside Maya. |
| The wire format is a bare dict with no schema | Backend models are aligned by hand; renaming one key breaks a consumer silently. |

A Maya scene is a document, but many of its properties are only decided at
runtime. That is the tension, and the fix is to **separate the runtime from the
document**.

#### Layers

```
┌──────────────────────────────────────────────────────┐
│ schema.py     pure dataclasses, zero Maya imports     │  ← the contract
│               SCHEMA_VERSION = "0.4.0"                │
├──────────────────────────────────────────────────────┤
│ collectors/   pluggable units, one per kind of data   │  ← the extension point
│               they only ever call SessionProtocol     │
├──────────────────────────────────────────────────────┤
│ adapters/     MayaSession: the only layer that        │  ← Maya is confined here
│               touches maya; FakeSession: a stand-in   │
├──────────────────────────────────────────────────────┤
│ pipeline.py   orchestration, error isolation, batch   │
└──────────────────────────────────────────────────────┘
```

Dependencies point one way only. There is exactly one custom base class —
`Collector` — and it is not a tree of node types.
**Extending means adding a collector file, not adding methods to a base class.**

#### Two axes: scan and query

The same collector classes serve both:

| | scan | query |
|---|---|---|
| Question | "tell me everything about this scene" | "give me **this**, with **these** arguments" |
| Parameters | each collector's defaults | supplied by the caller |
| Result | `SceneDocument` | `QueryResult` |
| Fits | batch ingestion, CI checks | interactive use, other tools calling in |

```python
scan_current_scene()                                     # everything
query("pose", roots=["|root"], time=0.0, space="world")  # one thing, with args
```

**No second registry, no second base class, no second set of payload types.**
A collector written for scanning is automatically queryable; a collector written
for querying automatically appears in scans with its defaults.

---

### Quick start

#### See the output shape without Maya

```bash
python -m mayakit demo
```

#### Scan the scene open in Maya

```python
from mayakit.scenedoc import scan_current_scene, dumps

doc = scan_current_scene()
print(dumps(doc))
```

#### Call one collector with arguments

```python
from mayakit.scenedoc import query

# a skeleton's pose at frame 0
r = query("pose", roots=["|root"], time=0.0)
for n in r.data.nodes:
    print(n.long_name, n.translate)

# world space, with matrices
r = query("pose", roots=["|root"], time=24.0, space="world", include_matrix=True)

# the bind pose
r = query("bind_pose")

# just one subtree of the DAG
r = query("dag_nodes", roots=["|geo_grp"], node_types=["transform"])
```

Same thing from a shell:

```bash
python -m mayakit query pose --param roots=|root --param time=0 --param space=world
```

**A selector that matches nothing is an error, not an empty answer.** Asking
about a node that is not there is a question with no answer, not a scene with
nothing in it:

```python
query("bind_pose", skin_clusters=["missingSkin"])
# status "error": no skinCluster named missingSkin in this scene.
# Pass strict_selectors=False to collect what does match and have the
# result marked partial.
```

Three collectors used to answer this three different ways, and the worst of
them returned a `SkinBindPose` with a blank uuid and no entries — a hollow
entity that reads like a finding about a rig with no bind pose.

For a batch pass over assets that change between shots, turn it off. What
matched is kept, the misses are recorded, and the result says so:

```python
r = query("dag_nodes", roots=["|hero", "|removed_last_week"],
          options=ScanOptions(strict_selectors=False))
r.status         # "partial"
r.ok             # False
r.data           # everything under |hero, still collected
r.diagnostics    # [Diagnostic(source="dag_nodes.roots",
                 #             target="|removed_last_week", ...)]
```

#### Query a file, without opening it yourself

`query` asks the scene that is already open. `query_file` takes a path — which
is the shape a backend actually wants, and the one that needs `mayapy`:

```python
from mayakit.scenedoc.standalone import query_file, query_many_file

r = query_file("hero.ma", "pose", roots=["|root"], time=0.0)
print(r.status, r.source.sha1, r.fingerprint)
```

Opening a scene costs seconds; the collectors cost milliseconds. Ask several
questions of one file and it opens once, and collectors that share a
dependency share its traversal too:

```python
results = query_many_file("hero.ma", [
    "meshes",
    "skeleton",
    ("pose", {"roots": ["|root"], "time": 0.0}),
])
```

Measured on a small scene, that is ~70% faster than three separate calls; the
gap widens with scene size, because the part it removes is the expensive part.

A file problem is never an exception and never an empty answer:

```python
r = query_file("deleted.ma", "meshes")
r.status        # "unavailable" -- not "ok" with an empty list
r.data          # None: we did not look, as opposed to looking and finding none
r.open_report   # says why, in the same shape a scan reports it
```

From a shell, with exit code 3 when the scene could not be read at all:

```bash
python -m mayakit query meshes --file hero.ma
```

#### Cache keys

Two answers with the same key and params used to be indistinguishable, so
nothing could tell which scene either was about. `fingerprint` is a digest of
everything that decides the answer — source content, collector and its
version, resolved params, every scan option, the collectors it depends on and
their versions and params, the schema, and the application that did the
reading.

**An empty fingerprint means *do not cache this*, so check it first:**

```python
if r.fingerprint:                 # empty = this answer is not reusable
    cache[r.fingerprint] = r.data # equal fingerprints, equal answers
```

It changes when the file changes, when the params change, when any option
changes, and when a collector or one of its dependencies is bumped because it
now computes differently. With `compute_file_hash=False` it falls back to size
and mtime — weaker, but still discriminating.

It is **empty**, deliberately, for:

| case | why |
| --- | --- |
| an unsaved scene | it changes under the artist's hands between one call and the next, so any key would collide two different scenes onto one entry |
| a saved scene with unsaved edits | the path, size, hash and mtime all still describe the file; the answer describes the session, which has moved on from it |
| `status` other than `ok` | an error, a blocked dependency or a half-read scene is not an answer to hand anyone later |
| an adapter that cannot say whether the scene is dirty | not knowing whether a result is reusable is not the same as knowing that it is |

#### Read a saved document back

```python
from mayakit.scenedoc import load

doc = load("out/shot_010.json")

doc.data["counters"].tris      # a SceneCounters object, not a dict
doc.data["meshes"][0].uv_sets  # a MeshInfo
doc.open_report.verdict        # an OpenReport
```

Without this the JSON would be write-only — no diffing two scans, no offline QC,
no feeding an archived scan into a script months later.

#### One reader for all four artifact types

A scan, a query result, a comparison and a rule report share an envelope
shape, so `read_artifact` handles any of them and every artifact declares its
own `kind`:

```python
from mayakit.scenedoc import read_artifact, write_artifact

artifact = read_artifact("out/anything.json")
artifact.kind    # "scene_document" | "query_result" | "diff_result" | "rule_report"
```

`load_artifact` (dict), `loads_artifact` (string) and `read_artifact` (file)
are the same codec, mirrored by `dump_artifact` / `dumps_artifact` /
`write_artifact`. Files written before `kind` existed are still recognised by
shape.

**A future major is refused, not guessed at.** The schema follows the rule it
states about itself — MINOR additive, MAJOR breaking — so 0.7 reads 0.9 and
declines 1.0:

```python
read_artifact("from_a_newer_mayakit.json")
# UnsupportedSchemaVersion: artifact declares schema 1.0.0 but this mayakit
# reads 0.7.0 ...
```

Pass `allow_future=True` to read it anyway. It is a real option for a salvage
job, and explicit because the values then get interpreted under this version's
rules.

**Round trips are lossless.** A document written by a newer mayakit carries
fields this one has never heard of, and load-then-dump used to drop them — an
archive quietly shrinking each time an older tool touched it. The worst case
was a field inside a *known* payload: counters that look right, minus a column.

```python
write_artifact(read_artifact("from_0_99.json"), "copy.json")
# copy.json still has every field the original did
```

Values you change after loading win; only fields with nowhere to live in this
version's schema come back from the original.

Old artifacts are migrated rather than merely tolerated — a 0.2.0 scan keeps
the Maya version it recorded, which the 0.3.0 field rename would otherwise
have dropped.

Compatibility runs both ways:

- a document from a **newer** mayakit → unknown payloads are **kept as raw dicts**, never dropped
- a document from an **older** mayakit → missing fields fall back to defaults

#### Check a document against rules

```bash
mayakit validate D:/shots --ruleset delivery      # scenes, saved scans, or both
mayakit validate --list-rulesets                  # what ships
```

```python
from mayakit.scenedoc import validate_file

report = validate_file("shot.mb", "delivery")
if not report.passed:
    for violation in report.errors:
        print(violation.name, violation.message)
```

Only rules of severity `error` fail the run — the difference between a gate and
a nag. Non-zero exit when one does, so it works in CI.

**Exit codes carry the third answer.** A CLI that CI reads is a CLI whose exit
codes are an API, so every verb uses the same four:

| | |
| --- | --- |
| `0` | ran to completion, and the answer is clean |
| `1` | ran to completion, and found something — differences, a failed rule, a file that would not open |
| `2` | could not be run as asked — arguments, request, format, schema, ruleset, or an I/O problem with an input. One actionable line, no traceback |
| `3` | **inconclusive**: it ran but reached no verdict, because a rule could not be evaluated, a read came back partial, or a key could not be compared |

A gate needs the fourth one; without it, "I could not finish checking" and "I
checked and it is clean" are the same green tick. And `1` versus `3` matters
in the other direction: a rule that *did not run* used to exit 1, reporting a
finding about a ruleset that never finished.

Expected errors are turned into one line at a single boundary, and which
errors those are is decided by the exception hierarchy rather than a list kept
up to date by hand — anything under `mayakit.core.errors.UserError` is the
user's to fix, anything else is a bug in mayakit and keeps its traceback.
Add `--debug` (or `MAYAKIT_DEBUG=1`) to see the traceback for an expected
error too.

**Rules are data, not code.** A backend can store them, version them per
project and ship them to a workstation without a release — and the same rule
then runs in Maya before the artist saves *and* on the server when the file
arrives, from one definition:

```json
{"name": "delivery", "version": "1", "rules": [
  {"id": "no_ngons", "description": "no face may have more than four sides",
   "key": "meshes", "field": "ngons", "op": "==", "value": 0},
  {"id": "triangle_budget", "key": "meshes", "field": "tris",
   "op": "<=", "value": 100000, "severity": "warning"}
]}
```

A rule pointed at a list is evaluated per entity, so one rule about ngons
produces one violation per offending mesh, named:

```
error    no_ngons                 |ngons|ngonsShape   no face may have more than four sides
warning  no_duplicate_short_names |grpA|dup           2 nodes share the short name 'dup'
warning  all_shapes_assigned      shading             every shape must have a material assigned
info     no_empty_groups          counters            empty groups should be cleaned up
```

A rule that cannot run is **skipped, reported, and does not pass** — a check
that quietly stopped running is the worst outcome of the three. An
`error`-severity rule that could not be evaluated makes `report.passed` false
and `report.status` `inconclusive`; a `warning`-severity one is recorded
without gating, because warnings inform either way.

Checks that no operator can express use `op="custom"` and name a function
registered with `@custom_check`. The rule stays serializable; the logic stays
in reviewed code.

#### Compare two of anything

```bash
mayakit diff approved.json wip.mb          # a saved scan against a scene
mayakit diff before.mb after.mb            # two scenes
mayakit diff a.json b.json                 # two saved scans -- no Maya needed
```

```python
from mayakit.scenedoc import compare_files

result = compare_files("approved.json", "wip.mb")
for entry in result.entries:
    print(entry.kind, entry.name, entry.changes)
```

Non-zero exit when anything differs, so it works as a CI gate — and exit `3`
when the comparison could not be completed. `result.status` is `equal`,
`changed` or **`inconclusive`**: if a payload key was present on only one side
or could not be compared, `changed: false` means "nothing differed among the
keys I managed to compare", which is not the same claim and is not reported as
though it were. `result.compared` lists the keys that actually ran.

**Entities pair on Maya's UUID**, which lives in the scene file and survives
renaming and reparenting — decided *per payload*, not per document, and
reported in `result.pairing_by_key`. A scan can legitimately hold re-exported
meshes beside untouched DAG nodes; one verdict for the whole document let the
meshes force name pairing everywhere, and a real reparent then vanished into
"no differences". So this:

```
renamed    skeleton.joints  |root|spine -> |root|spine_01
renamed    skeleton.joints  |root|spine|head -> |root|head   translate: [0,7,0] -> [0,12,0]
modified   skeleton.joints  |root                            radius: 1.0 -> 4.0
added      dag_nodes        |prop
```

rather than a wall of deletions and additions. A node that was renamed, moved
*and* edited is **one** entry, not three.

Comparison is driven by the payload shape, so a collector you add gets diffed
without registering anything — the same deal it already gets for scanning,
querying and loading.

#### Comparing across sources

An FBX export shares no UUIDs with the scene it came from — measured, not
assumed. `pair_by="auto"` (the default) notices and falls back to matching on
name:

| comparing a scene with its own FBX export | result |
|---|---|
| forced `pair_by="uuid"` | 22 added + 22 removed |
| default `auto` → name pairing | 2 differences |
| `cross_source` preset, skeleton and meshes only | **1 line: `max_influences: 2 -> 5`** |

```bash
mayakit diff base.ma base.fbx --preset cross_source --only skeleton meshes
```

Presets live in `mayakit.scenedoc.compare.IGNORE_PRESETS`: `cross_source`,
`names` (labels churn during review while the rig does not), `volatile` (the
scan's own bookkeeping). They merge, and any keyword argument wins over all of
them.

**Except where merging them cancels them.** `cross_source` pairs entities by
name; `names` ignores the name fields. Asked for together they say "match
these up by their names, and pay no attention to their names" — which never
produced a false clean (a rename came back as removed plus added) but had
nothing in the output to explain why. That is refused now, as the general
rule rather than as that pair of presets, so the same mistake made by hand is
caught too:

```text
pair_by="name" matches entities by their names, but these are ignored:
dag_nodes.long_name, dag_nodes.short_name, meshes.long_name … — so the
comparison would be told to pair on a label it was also told to disregard.
Use pair_by="uuid" or "auto" to ignore names, or stop ignoring them to pair
on them
```

`pair_by="auto"` can still *arrive* there — no shared uuids on some list, so
it falls back to the label the caller ignored. That is not refused, because
`names` on its own is a legitimate and common request; the result says so
instead, under `dag_nodes._identity_ignored`, and is `inconclusive` rather
than a clean answer.

#### Where the data came from

Three ways in, and they are not interchangeable:

| `read_mode` | |
| --- | --- |
| `maya_session` | read out of a Maya session somebody is working in |
| `maya_native_open` | a `.ma`/`.mb` opened headless by this process |
| `maya_fbx_import` | an `.fbx` **imported** through Maya's FBX translator |

They used to share one `source_app` value of `"maya"`, so a consumer deciding
whether two documents could be compared — or whether an answer could be reused
— had nothing in the document to decide it with. `Generator.read_mode` and
`Generator.reader_version` (the FBX plugin's, when one was involved) now say,
and both are part of the query [cache key](#cache-keys): two FBX plugin
versions can interpret one file differently, and an answer from one must not
be served for the other.

`maya_fbx_import` describes **Maya's interpretation of the file, not the
file**. FBX version, ASCII/binary, exporter signature and the take stack do
not survive the translation and are simply absent — reading those would want a
separate FBX adapter, not a claim on this payload. A Maya-vs-FBX comparison is
therefore cross-source and cannot use Maya UUIDs; that is what the
`cross_source` preset is for.

**A saved scene someone has since edited is not that file.** It reports the
same path, size, hash and mtime — measured on 2026 and 2027, the sha1 is
identical — so `SourceFile.has_unsaved_changes` is the only thing that can
tell them apart. `None` there means the adapter could not say, which is not
the same as `False`.

**Unsupported is not empty.** A collector declares
`supported_read_modes` when it needs a particular source, and asked of another
it reports `unavailable` with a reason rather than an empty payload — "I could
not ask" and "there are none" are different answers, and only one of them is a
fact about the scene.

#### A node can be in several places at once

`dag_nodes` has one record per Maya UUID, which is one record per *node* — and
`cmds.ls(dag=True)` returns each node exactly once, however many places it
occupies. So instancing a group put its whole subtree somewhere new and the
document said nothing: every path after the first was simply absent, with
`is_instanced=True` the one hint that anything was missing.

`dag_instances` is the second layer: one record per **path**.

```json
{"instance_id": "67c6ccdf2ef29184", "uuid": "FC6D3EA8-416D-…",
 "long_name": "|copy|src|srcShape",
 "parent_instance_id": "676ae7b934026fdc", "depth": 2}
```

**Identity here is the path, not the node** — and a real scene rules out the
obvious alternative. Instance a group twice and the shape's three paths all
report the *same* `parent_uuid`, because the parent is instanced too, so uuid
plus parent cannot tell them apart. What can is the chain of node uuids from
the root, which is what `instance_id` digests. That survives what a long path
does not: renaming any ancestor leaves it unchanged, and so does Maya
renumbering its instances.

It is not a second copy of `dag_nodes`: a node with one path is already fully
described there, so **a scene with no instancing produces an empty payload.**

A reparented instance comes back as a removed path and an added one, which is
the honest answer rather than a limitation — a path *is* its ancestry, so
moving it makes it a different path, and Maya has no persistent identity for
"this particular instance" to say otherwise. The node-level `reparented` entry
in `dag_nodes` is what names the edit.

#### Discover what each collector accepts

```bash
python -m mayakit collectors --params
```

```
pose            v2    requires: dag_nodes    Transforms of a node set...  [opt-in]
                  roots                  List[str]        default=[]      of str
                  include_descendants    bool             default=True
                  node_types             List[str]        default=['joint'] of str
                  time                   Optional[float]  default=None    or null
                  space                  str              default='local' one of: local, world
                  include_matrix         bool             default=False
```

The interface is **self-describing**: `mayakit.scenedoc.available()` returns
the same thing as JSON — per parameter its `kind`, `required`, `nullable`,
`default`, `items`, `choices` and `help`, and per collector its version,
dependencies, whether it runs by default, and what it returns:

```json
{"key": "pose", "version": "2", "requires": ["dag_nodes"],
 "default_enabled": false, "payload": {"type": "Pose", "many": false},
 "params_schema_version": "1.0.0",
 "params": [{"name": "space", "type": "str", "kind": "str",
             "required": false, "nullable": false, "default": "local",
             "choices": ["local", "world"], "help": ""}]}
```

**It is generated from the declarations the validator reads**, never written
alongside them. That is the whole design constraint: `pose.space` has been
restricted to local/world since the metadata existed, and discovery used to
report only its type and default — so a frontend built from it offered a free
text field, and the caller learned the truth from a rejection. Two hand-kept
sets of rules drift, and the one that drifts silently is the one nobody runs.

#### One bad file must not take the batch with it

`scan` walks a whole library inside one long-lived `mayapy`, which is the fast
way and has one failure mode it cannot handle from inside: if Maya hangs or
dies on a native open, no Python timeout in that process can interrupt it, and
every file after the bad one is never looked at. A thousand-file pass stops at
file 37 and nothing says why.

```bash
mayapy -m mayakit scan D:/library -o D:/out --isolate --timeout 300
```

`--isolate` reads each file in its own child process with a wall-clock
deadline. On a timeout or a crash the parent kills the child, records which of
the two it was, and goes on:

```text
  ! timeout: the scan did not finish within 300s and the worker was killed
  ! crashed: the worker exited with -1073741819: Fatal Error. Attempting to save in …
```

Both are `verdict`s of their own rather than `failed`, because they want
different things done about them: a timeout usually wants a longer deadline or
a look at the scene, a crash wants the stderr. Both come back as
`status="unavailable"` — a scan that never happened must not be filed next to
one that found nothing — and both still produce a document, so a caller
zipping paths to results is never short an entry.

The cost is one Maya startup per file, seconds each. Worth it for a nightly
library pass, not for three files, which is why it is opt-in.

**This is reliability, not a sandbox.** It stops one bad scene taking the
batch down, and with `execute_script_nodes=False` (the default) it reduces the
attack surface of reading files you did not author. It is not a substitute for
a restricted account, no network, a container or a VM: the child is a full
Maya with your credentials and your filesystem, and a scene that gets code
running inside it has all of that.

`--trusted` turns script-node execution back on. A `.ma` is a script; that
flag hands the file the process. Only for scenes you authored or trust.

#### Batch scan a directory, headless

```bash
"C:/Program Files/Autodesk/Maya2026/bin/mayapy.exe" -m mayakit scan D:/scenes -o D:/out
```

#### Reading FBX

`.fbx` files are picked up by `scan` and `check` alongside `.ma`/`.mb`, with no
extra dependency — `fbxmaya` ships with Maya. All ten collectors run unchanged,
because the schema models *concepts*, not Maya node types.

```bash
mayapy -m mayakit check D:/exports          # .ma, .mb and .fbx in one pass
```

**It is a translation, not a reading.** An FBX is *imported* through Maya, so
what you measure is Maya's interpretation of the file. Documents read this way
are stamped `generator.source_app = "maya-fbx"` rather than `"maya"`, so a
consumer can tell which kind of evidence it is holding.

Measured on a round trip — scene → FBX → re-import → scan:

| | preserved |
|---|---|
| counters (meshes, verts, tris, uvs, joints, materials, textures) | identical |
| bind pose (per-influence world matrices) | identical |
| blend shape names and targets | identical |
| materials, texture paths, node names | identical |

One thing that does **not** survive, and was only visible once the weight
fingerprints existed: **negligible skin weights are pruned**. An influence
holding a total weight of 0.02 across 25 vertices came back with none, and
`max_weights_per_vertex` dropped from 2 to 1. Structurally the round trip is
faithful; numerically it is not, below the exporter's threshold.

What else does not survive, because it lives below Maya's node graph:

- the FBX version, and whether the file is ASCII or binary
- the exporter signature (e.g. `FBX SDK/FBX Plugins version 2020.3.9`)
- **takes** — Maya flattens animation stacks on import
- embedded media

If you need those, they require reading the file directly rather than through
Maya. The architecture is ready for it: a second session behind the same
`SessionProtocol` would need no change to the schema or the collectors.

#### Triage: which files open, and what do they complain about?

```bash
"C:/Program Files/Autodesk/Maya2026/bin/mayapy.exe" -m mayakit check D:/scenes -o report.json
```

```
[1/5] .../broken_reference.ma
      errors    0 error(s) 2 warning(s)
[2/5] .../garbage.ma
      failed    0 error(s) 0 warning(s)  RuntimeError: Unrecognized file.
[3/5] .../healthy.ma
      ok        0 error(s) 0 warning(s)
checked 5 file(s): errors=2, failed=1, ok=1, warnings=1
```

Cheaper than a scan — no collectors run. Exit code is non-zero when anything
failed to open, so it drops straight into CI.

#### Run the tests (no Maya needed)

```bash
python -m pytest tests -q
```

---

### The document

```jsonc
{
  "schema_version": "0.4.0",
  "generated_at": "2026-08-22T03:39:49+00:00",
  "generator":   { "tool": "mayakit", "source_app": "maya", "source_app_version": "2026",
                   "python_version": "3.11.9", "host": "..." },
  // facts about the file on disk: true forever
  "source":      { "path": "...", "sha1": "...", "size_bytes": 44552,
                   "path_is_ascii": true, "exists": true },
  // what this Maya build made of it: true only for this version, these plugins
  "open_report": { "opened": true, "verdict": "errors", "error": null,
                   "error_count": 1, "warning_count": 2,
                   "missing_references": ["X:/gone/rig.ma"],
                   "unresolved_plugins": ["someStudioPlugin"],
                   "unknown_node_count": 1,
                   "diagnostics": [
                     { "severity": "warning", "count": 8213, "source_line": 4821,
                       "message": "Unrecognized node type 'fooNode'; preserving..." }
                   ] },
  "data": {
    "scene_settings": { "up_axis": "y", "linear_unit": "cm", "fps": 24.0, ... },
    "dag_nodes":      [ { "uuid": "...", "parent_uuid": "...", ... } ],
    "meshes":         [ { "uuid": "...", "tris": 192, "ngons": 0, ... } ],
    "shading":        { "materials": [...], "textures": [...], "unassigned_shape_uuids": [...] },
    "cameras":        [ ... ],
    "skeleton":       { "joints": [...], "skin_clusters": [...] },
    "blend_shapes":   [ ... ],
    "bind_pose":      { "skins": [...], "dag_poses": [...] },
    "counters":       { "tris": 1172, "ngons": 2, "joints": 3, ... }
  },
  "reports": [
    { "key": "meshes", "version": "1", "status": "ok", "duration_ms": 2, "error": null }
  ]
}
```

---

### Key design decisions

#### 1. Fingerprints, because counts are not enough

`MeshInfo.topology_hash` and `SkinClusterInfo.weights` exist because of a
measured blind spot. Repaint every weight on a character and the influence
list, every count and `max_influences` all stay identical — so a comparison
reported **`changed=False`**. Same for a mesh deleted and rebuilt.

The weight summary is an aggregate — per influence a vertex count, a sum and a
hash — never per-vertex weights. That is enough to notice a repaint while
staying small enough to store for every asset in a library. It costs about
0.8 µs per weight (4 ms for a small mesh, 346 ms for 432k weights) and is on by
default; `ScanOptions(include_skin_weights=False)` turns it off.

#### 2. Node identity is Maya's UUID, not the name

The UUID from `cmds.ls(node, uuid=True)` is **stored inside the .ma/.mb file**.
It survives renames, reparenting and re-saving. So every relationship in the
document — parent, skin influence, material assignment — is expressed as a UUID,
and names are carried only as human-readable labels.

For a backend this is the difference between a diff that shows real changes and
one that claims the entire scene was rebuilt.

> A trap worth knowing: `cmds.ls(uuid=True)` **without node arguments silently
> returns names, not UUIDs** — and returns exactly as many of them as there are
> nodes, so a length check alone happily pairs every node with its own name.
> `MayaSession._prime_uuid_cache()` validates the *shape* of the results, not
> just the count.

#### 3. The bind pose comes from `skinCluster.bindPreMatrix`, not `dagPose`

`bindPreMatrix[i]` is the **inverse world matrix** of influence `i` at bind
time, and it is what the deformation actually multiplies by. Invert it and you
have where that joint stood when the skin was bound. It cannot go stale — if it
were wrong, the mesh would already be deforming wrong.

`dagPose` nodes get deleted and can silently go out of date, but they can also
cover joints no skinCluster binds. So **both are recorded**: when the two
disagree, that is exactly the rig that is about to export wrong.

Verified: with the rig posed far away from its bind pose (root moved 30 units,
spine rotated 45°), `bind_pose` still returns the original bind positions
exactly.

#### 4. `opened == true` does not mean the file is fine

The most underestimated part of this tool. Maya opens all of these **without
raising anything at all**:

- a reference whose file does not exist
- a scene needing a plugin this machine does not have — its nodes degrade to
  `unknown` and are **permanently lost on the next save**
- broken texture paths

It writes them to the script editor as warnings and carries on.
**Code that only catches exceptions will report those files as healthy.**

So `open_scene()` wraps the open in an output callback (`MCommandMessage`),
captures every warning and error, adds structured checks (do the references
resolve, `unknownPlugin -q -list`, `ls -type unknown`) and collapses the lot
into one `verdict`:

| verdict | meaning |
|---|---|
| `ok` | clean |
| `warnings` | opened, with warnings or unknown nodes |
| `errors` | opened, but with errors / missing references / unavailable plugins — **the data is already incomplete** |
| `failed` | would not open at all; `error` holds the exception |
| `not_attempted` | no open was tried (e.g. scanning the already-open scene) |

Diagnostics are **de-duplicated and counted**. Not for tidiness: a scene with a
missing reference emits one warning per node in it — tens of thousands of them.
And Maya's raw message looks like this:

```
file: D:/shots/sh010/anim.ma line 4821: Unrecognized node type 'fooNode'; ...
```

That `line 4821` differs every time. Without stripping the prefix first, tens of
thousands of semantically identical warnings become tens of thousands of
*distinct* strings, each carrying its own full copy of the scene path. Stripped,
they collapse to a single row with `count: 8213`.

#### 5. One failing collector never costs you the document

Scanning a few hundred production files will always hit a broken reference, a
missing plugin, a node from an older Maya. `run_collectors()` catches each
collector individually, records it in `reports`, and emits everything else.

Even a **file that cannot be opened produces a document** — with the full
on-disk facts and an `open_error` — because "this file is broken" is precisely
what the consumer needs to know.

#### 6. The DAG is a flat list with parent pointers, not a nested tree

It maps directly onto a self-referencing foreign key, diffs cleanly, and cannot
blow the recursion limit on a deep rig.

#### 7. Parameters travel back with the result

`QueryResult.params` and `CollectorReport.params` carry the **fully resolved**
parameters, defaults included. A pose payload is uninterpretable without knowing
which frame and which space it was sampled in — and a backend cannot use it as a
cache key if it cannot see it.

#### 8. A misspelled parameter is an error, not a silent no-op

```
>>> query("pose", tiem=0)
ParamError: unknown parameter(s) tiem; PoseParams accepts: roots,
            include_descendants, node_types, time, space, include_matrix
```

Caller mistakes raise (fail fast); **scene problems** go into the
`QueryResult.error` envelope. Those are different kinds of thing and deserve
different handling. Everything raised inherits from `MayakitError`, so
`except MayakitError` catches all of it without swallowing a `KeyError` from
your own code.

#### 9. The library does not write to its host's log

The package attaches a `NullHandler` and stays silent. Every log call is at
**DEBUG** level, because Maya configures the root logger — anything above DEBUG
from a library lands in the artist's script editor. When you need to look:

```python
import logging
logging.basicConfig()
logging.getLogger("mayakit").setLevel(logging.DEBUG)
```

The Maya queries that `MayaSession._safe` swallows print full tracebacks at that
point.

---

### Extending

A complete runnable example lives in
[examples/custom_collector.py](examples/custom_collector.py):

```python
from dataclasses import dataclass, field
from typing import List, Optional

from mayakit.scenedoc import Collector, register


@dataclass
class MyParams:                              # this is the interface definition
    roots: List[str] = field(default_factory=list)
    time: Optional[float] = None
    strict: bool = True


@register
class MyCollector(Collector):
    key = "my_thing"                         # top-level key in the document
    version = "1"                            # bump when the payload shape changes
    requires = ("dag_nodes", "meshes")       # dependencies, sorted automatically
    params_class = MyParams                  # having this makes it queryable

    def collect(self, ctx):
        params = ctx.params                  # already validated and coerced
        for node in ctx.get("dag_nodes"):    # reuse what others already collected
            ...
        return result                        # return a dataclass
```

Four steps: **subclass `Collector` → define `params_class` (optional) →
`@register` → make sure the module gets imported.** Not a line of mayakit
changes, and the new collector immediately works both ways:

```python
query("my_thing", roots=["|geo_grp"], time=0)         # with arguments
scan_current_scene(ScanOptions(include=["my_thing"]))  # as part of a full scan
```

`params_class` is an ordinary dataclass. The framework validates the parameter
names, coerces values against the annotations (`"0"` → `0.0`, `"true"` → `True`,
`"a,b"` → `["a","b"]`), and hands the resolved values back to the caller.

Note that the example **never touches `maya.cmds`** — it reads what the
`dag_nodes` collector already produced. That makes it nearly free in a batch run
and unit-testable against `FakeSession`.

When you genuinely need a new Maya query, add a semantic method to
`MayaSession` (and its counterpart to `FakeSession`), or use the escape hatch
`ctx.session.cmds`. The escape hatch costs you the ability to test that
collector outside Maya — a conscious trade, not an accident.

#### Overriding a builtin

Say so, and it is yours:

```python
@register(override=True)
class StudioDagNodes(Collector):
    key = "dag_nodes"
    ...
```

**The marker is the whole point.** Registration used to be last-wins, which
made the winner a fact about import order — and mayakit imports its own
builtins lazily, so "last" was usually mayakit. A studio package registered
its `dag_nodes`, then touched anything that reached
`mayakit.scenedoc.collectors`, and got the builtin back, with nothing anywhere
saying the override had been undone. Measured before the fix:

```text
after the studio registers:   counters -> vstudio-1
after mayakit's builtins:     counters -> v1
```

So now:

| | |
| --- | --- |
| `register(c)` on a free key | registered |
| `register(c, override=True)` | replaces, and **keeps** the key — a later plain registration of it is ignored, so import order stops mattering in both directions |
| `register(c)` on a key someone else registered plainly | `DuplicateCollectorError` — two parties believe they own it and neither said so |
| a second `override=True` for one key | `DuplicateCollectorError` — two packages fighting, and deciding that by import order is what this prevents |

`registry.overrides()` lists what a package has taken over, and
`registry.unregister(key)` gives it back.

---

### Why it tests without Maya

Collectors only ever talk to `SessionProtocol`
([adapters/protocol.py](src/mayakit/scenedoc/adapters/protocol.py)). `FakeSession`
implements the same interface over an in-memory scene graph, so:

- the suite runs in a plain interpreter in under a second — no licence, no Maya;
- the only files that genuinely need a real Maya to verify are
  `maya_session.py` and `standalone.py`.

```bash
python -m pytest tests -q
```

**And the limit of that.** Everything in `maya_session.py` is a claim about
what `maya.cmds` and OpenMaya actually do, and the suite cannot check a claim
like that — `FakeSession.world_matrix` reads a dict, and no dict has ever
refused a shape. `cmds.xform` does: it fails on every shape, which made a
healthy cube scan report `partial` while all 500 tests stayed green.

So `scripts/verify_maya.py` holds the checks only a real Maya can answer, and
it is run against **both** supported versions:

```bash
"C:/Program Files/Autodesk/Maya2026/bin/mayapy.exe" scripts/verify_maya.py
"C:/Program Files/Autodesk/Maya2027/bin/mayapy.exe" scripts/verify_maya.py
```

Each check prints what it measured, not only whether it liked it, so a run is
evidence rather than a tick. A behaviour earns a place there when the fake
session cannot reproduce it because the bug lives in the real API.

**`scripts/benchmark_diff.py` measures the diff at scale.** Not part of the
suite on purpose: it takes about four minutes at the full matrix, and a
wall-clock assertion on shared hardware is a flaky test wearing a performance
costume.

```bash
python scripts/benchmark_diff.py              # 10k / 50k / 100k x 3 layouts
python scripts/benchmark_diff.py --sizes 10000 --json rows.json
```

Measured on this machine (Windows, CPython 3.14), two documents differing by
exactly one reparent:

| entities | seconds | entities/s | peak MiB |
| --- | --- | --- | --- |
| 10,000 | 1.37 | 7,280 | 15 |
| 50,000 | 6.9 | 7,250 | 78 |
| 100,000 | 14.2 | 7,020 | 158 |

The numbers themselves are not the point — a different machine gets different
ones. **The flat throughput column is the point**: pairing is a dict lookup,
so a diff is linear in entity count, and a change that quietly makes it
quadratic turns a 100k rig from seconds into an afternoon. The script's floor
is set far below any real measurement so that it reads as a change of
complexity rather than a slower laptop.

Three identity layouts run at each size, because pairing is what is being
measured: both sides in order, the right side reversed (pairing must not
depend on position — this is the case that caught the false negative in #7),
and half the entities without a uuid so hybrid pairing runs both strategies
over one list. Every row also asserts the one reparent came back as the one
result; a fast diff that lost the edit would not be an improvement.

**Recommended scale**: up to ~100k entities per payload is comfortable in
process. Beyond that, compare by `--only <key>` to work a payload at a time,
or run the comparison on saved documents off the workstation — it needs no
Maya.

**`scripts/check.py` is the gate.** It runs the suite on **Python 3.9 through
3.13** via `uv`, plus `ruff`, `mypy` against the 3.9 floor, a build, and a
clean-venv install that drives the CLI through the wheel — 17 checks, about
two minutes.

`mypy` runs *on* the 3.9 interpreter as well as *for* it, so the floor check
does not depend on which environment you happen to have active. mypy 2.x no
longer accepts 3.9 as a target at all; under 3.9 the resolver can only choose
a mypy that runs there, and a mypy that runs on 3.9 can check 3.9:

```bash
python scripts/check.py           # the matrix, ruff, mypy, build, clean install
python scripts/check.py --quick   # this interpreter only
```

Publishing goes through `scripts/release.py`, which puts that gate in front of
the upload **and one behind it**: after the index confirms the version, it
installs `mayakit==<version>` from the real PyPI into a clean venv and runs
the public API this README documents. The index listing a version is not the
same as pip being able to install it, and installing is not the same as the
documented example working — and PyPI being a release behind the README is
exactly the gap that [#25](https://github.com/narutozb/mayakit/issues/25)
reported.

```bash
python scripts/release.py --check    # everything except the upload
python scripts/release.py --test     # to TestPyPI
python scripts/release.py            # to PyPI, for real
```

It refuses a dirty or unpushed tree, refuses a version already on PyPI — the
one mistake here that cannot be undone, because a version number is spent even
if you delete the release — requires a CHANGELOG entry, and asks you to *type*
the version rather than answer a y/n prompt by reflex. Credentials stay
twine's business: `~/.pypirc`, or `TWINE_USERNAME=__token__` with a
`pypi-...` token, or twine's own prompt.

`.github/workflows/ci.yml` defines the same checks (and adds Windows at both
ends of the range, since the CLI's path comparison is what differs across
platforms), but its push and pull-request triggers are **switched off** while
this account's monthly Actions minutes are exhausted — a red tick nobody can
act on is worse than no tick. Uncomment the two triggers when the allowance
resets. A skipped test fails the job there: the packaging assertions used to
skip on exactly 3.9 and 3.10, the two versions most likely to break.

Worth knowing why the matrix earns its two minutes: annotate one dataclass
field as `str | None` and 3.9 fails four tests while 3.13 stays green, because
`core.deserialize` resolves annotations at runtime with `get_type_hints`. On a
modern machine — and in both mayapy versions, which are 3.11 and 3.13 — that
break is invisible.

---

## Verification

| Check | Result |
|---|---|
| Maya 2026 (Python 3.11.9) | all 10 collectors `ok` |
| Maya 2027 (Python 3.13.9) | same code, same scene, identical output |
| Batch scan over a directory containing a corrupt file | the bad file yields `opened: false` + `open_error`; the batch continues |
| `query("pose", time=0/24)` | correct samples, and **current time is not moved** (parked at frame 12, still 12 afterwards) |
| `query("pose", space="world")` | world matrix decomposition correct (chain tip after a 45° rotation matches exactly) |
| `query("bind_pose")` | bind positions recovered exactly with the rig posed away from them; influence UUIDs resolve |
| `check` against 5 deliberately damaged scenes | see below — all classified correctly |
| `check` against 6 FBX files (binary, ASCII, empty, truncated, text, missing) | all classified correctly |
| FBX round trip (scene → fbx → import → scan) | counters, bind pose, blend shapes, materials, textures all identical |
| `diff` on a scene vs an edited copy | rename, reparent, value edit and addition each reported once |
| `diff` on a scene vs its own FBX export | auto-pairing falls back to name; noise collapses to one real finding |
| repainted weights / rebuilt mesh | invisible without the fingerprints, caught with them |
| `validate` on a scene with planted faults | missing texture, ngons, duplicate names, unassigned shapes and empty groups all caught, each naming its offender |
| a ruleset serialised and reloaded | 8 rules round-trip and behave identically |
| Wheel installed into a clean venv | CLI, pipeline and round-trip all work from outside the source tree |
| Wheel installed into `mayapy` | same, with no log noise in the script editor |
| The full suite on 3.9 / 3.10 / 3.11 / 3.12 / 3.13 | 321 pass on each, so `requires-python = ">=3.9"` is a measured claim rather than a stated one |
| Unit tests (no Maya) | 500 passed |

#### What `check` found

Five scenes built to be broken on purpose (the test script creates them):

| File | opened | verdict | Detected |
|---|---|---|---|
| `healthy.ma` | ✅ | `ok` | — |
| `missing_texture.ma` | ✅ | `warnings` | 1 warning |
| `broken_reference.ma` | ✅ | `errors` | `missing_references: [_temp_ref.ma]` |
| `unknown_plugin.ma` | ✅ | `errors` | `unresolved_plugins: [someStudioPlugin]`, 1 unknown node, plus Maya's own "Errors have occurred while reading this scene that may result in data loss." |
| `garbage.ma` | ❌ | `failed` | `RuntimeError: Unrecognized file.` |

Note that the first four all have **`opened == true`**. That is why "can it be
opened" is not a sufficient question.

The FBX cases fail the other way round, and needed a fix:

| File | opened | verdict | Detected |
|---|---|---|---|
| `healthy.fbx` (binary) | ✅ | `ok` | — |
| `ascii.fbx` | ✅ | `ok` | — |
| `truncated.fbx` | ❌ | `failed` | `FBX import produced no nodes; the file is not a readable FBX` |
| `garbage.fbx` (plain text) | ❌ | `failed` | the translator's own error |
| `empty.fbx` (0 bytes) | ❌ | `failed` | the translator's own error |
| `actually_text.fbx` (XML) | ❌ | `failed` | the translator's own error |

`cmds.file(i=True, type="FBX")` **does not raise** on any of the bottom four —
it writes an error to Maya's output stream and returns normally. So `opened` is
decided by whether nodes actually appeared, not by whether an exception was
thrown.

---

### Notes for the backend / frontend

- **Store `schema_version`.** Use it to drive migrations rather than guessing.
- **Key on `(scene_id, uuid)`**, never on `long_name` — that changes on every
  rename.
- **Give `counters` its own table.** A list page reads only that, instead of
  touching tens of thousands of `dag_nodes` rows.
- **Store `reports` too.** "the `meshes` collector failed" and "this scene has
  no meshes" are completely different facts, and a consumer that only has `data`
  cannot tell them apart.
- **`source.sha1` works as an idempotency key** — skip a file already scanned,
  or use it to decide whether a re-scan is needed.
- **Store `source` and `open_report` separately.** `source` is disk truth and
  stays true; `open_report` is only true for that Maya version with those
  plugins. Merged into one table, "which files broke when we moved to Maya 2027"
  becomes a painful question.
- **`open_report.verdict` is ready to be a status column**; leave `diagnostics`
  for the detail view.
- **The package version and the schema version are independent.** Consumers
  should pin to `schema_version` (`mayakit.scenedoc.SCHEMA_VERSION`), not to the pip
  release — the code can ship many times without the document changing.
- **Store `params`.** Pose data is meaningless detached from its `time` and
  `space`, and those values are naturally part of a cache key.
- **`mayakit.scenedoc.available()` can be served straight to a frontend** to generate
  parameter forms or validate requests, instead of transcribing the parameter
  list on both sides.

---

### Not included (on purpose)

- **Animation curves** (keyframes, tangents). Whole-curve storage costs far more
  space than it is worth until there is a concrete need for it; the computed
  result is better left in Maya. Note that **single-frame sampling already
  works** — `query("pose", time=N)`. What is missing is the whole curve, not the
  frame.
- **Vertex-level data** (per-point weights, positions) — involves real
  computation and probably does not belong in the same document.
- **UV shell / overlap / non-manifold analysis** — needs per-face iteration and
  is expensive. When added it should be an opt-in collector
  (`default_enabled = False`, the pattern `pose` already uses).
- **Incremental scanning** (collecting only what changed).
- **Writing back to Maya.** This is read-only, deliberately.
- **Recursing into references** — `include_references` records the reference
  list without descending into it.

---

## Layout

```
src/mayakit/
├── __about__.py              # the single definition of the version
├── __init__.py               # umbrella: identity + module list, nothing else
├── cli.py                    # mounts each module's verbs onto one parser
├── core/                     # ← shared framework, no DCC knowledge at all
│   ├── schema.py             # the data contract (pure dataclasses)
│   ├── diff/                 # comparing two documents
│   │   ├── schema.py         # DiffResult / DiffEntry / FieldChange
│   │   ├── options.py        # DiffOptions: pairing, tolerances, ignores
│   │   └── engine.py         # the shape-driven comparison
│   ├── rules/                # checking one document against a ruleset
│   │   ├── schema.py         # Rule / RuleSet / Violation / RuleReport
│   │   ├── operators.py      # the closed set of comparisons a rule may use
│   │   ├── serialize.py      # rulesets to and from JSON
│   │   └── engine.py         # evaluation, and custom-check registration
│   ├── base.py               # Collector base class + topological sort
│   ├── registry.py           # CollectorRegistry (one instance per module)
│   ├── params.py             # parameter validation, coercion, self-description
│   ├── options.py            # the ScanOptions every source understands
│   ├── errors.py             # the MayakitError hierarchy
│   ├── serialize.py          # dataclasses → JSON
│   ├── deserialize.py        # JSON → typed objects
│   ├── runner.py             # run collectors, isolate failures, build the doc
│   └── query.py              # parameterised single calls
└── scenedoc/                 # ← the Maya scene-document module
    ├── __init__.py           # public API (re-exports core + Maya specifics)
    ├── compare.py            # path→document, and the measured diff presets
    ├── rules.py              # shipped Maya rulesets and custom checks
    ├── registry.py           # this module's registry and @register
    ├── options.py            # ScanOptions + the Maya-only knobs
    ├── diagnostics.py        # Maya message prefix parsing (pure, testable)
    ├── documents.py          # load()/loads() bound to this registry
    ├── adapters/
    │   ├── protocol.py       # SessionProtocol — all a collector may call
    │   ├── maya_session.py   # the real Maya implementation
    │   ├── output_capture.py # catches Maya's warnings/errors during an open
    │   └── fake_session.py   # the no-Maya stand-in + demo scene
    ├── collectors/           # 10 builtin collectors, incl. pose / bind_pose
    ├── pipeline.py           # scan_current_scene (Maya entry point)
    ├── query.py              # query() bound to this registry and session
    ├── standalone.py         # headless batch scanning through mayapy
    └── cli.py                # this module's subcommands
```

Four rules, all **enforced by AST scans** in
[tests/test_layering.py](tests/test_layering.py) rather than left to discipline:

1. `mayakit.core` imports no DCC library.
2. `mayakit.core` does not import a module — dependencies point one way only.
3. Only `scenedoc/adapters/` and `scenedoc/standalone.py` may import `maya`.
4. Each module owns a distinct `CollectorRegistry`.

### Where new things go

- a **new source** (FBX read directly, USD, …) → a module beside `scenedoc`;
- a **new kind of information** from an existing source → a collector in that
  module;
- a **new thing to do with a finished document** (validation rules, an export
  format) → a subpackage under `core/`, beside `diff/`.

### Adding a module

A module is a subpackage that supplies three things on top of `mayakit.core`:

1. a **session** — the adapter that talks to the source, behind a protocol,
   with a fake counterpart so collectors stay testable;
2. a **registry** — `CollectorRegistry("yourmodule")` plus its `.decorator()`,
   so its collectors cannot collide with another module's;
3. its **collectors**, plus any source-specific options or payload types.

If it has command line verbs, add a `cli.py` with `VERBS` and
`register_subcommands(subparsers)`. Add the name to `mayakit.MODULES` and the
verbs mount automatically. Two modules claiming the same verb is a hard error
rather than one silently shadowing the other — checked before registration,
because Python 3.9 and 3.10 (Maya 2023 and 2024) let argparse overwrite
silently where 3.11+ raises.

Everything a module needs to reuse is already source-agnostic: `MeshInfo`,
`JointInfo`, `Skeleton`, `BindPose`, `Pose` and the document envelope describe
concepts, not Maya. A few names still carry Maya's vocabulary (`dag_nodes`,
`skin_clusters`, `dag_poses`) because that is where they were first written;
neutralising them is a deliberate schema-1.0 decision rather than something to
do piecemeal.

`__about__.py` is the single definition of the version; `pyproject.toml` reads
it via `dynamic = ["version"]`.

---

## Releasing

The version lives in exactly one place,
[src/mayakit/\_\_about\_\_.py](src/mayakit/__about__.py). Change it there and
nowhere else — [tests/test_packaging.py](tests/test_packaging.py) fails if a
hard-coded copy reappears.

Publishing goes through one command, which runs the whole gate first:

```bash
python scripts/release.py --check   # everything except the upload
python scripts/release.py --test    # TestPyPI
python scripts/release.py           # PyPI, for real
```

Running `twine upload` by hand skips every check above — the version-already-
taken check most of all, and that is the one mistake nothing can undo.

See [CHANGELOG.md](CHANGELOG.md) for what changed.

---

## License

MIT — see [LICENSE](LICENSE).
