agent-manifesto-kit 1.2.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +101 -1
  2. package/collection/bundles/blender-3d/README.md +138 -0
  3. package/collection/bundles/blender-3d/agents/visual-reviewer.md +58 -0
  4. package/collection/bundles/blender-3d/skills/blender-asset/SKILL.md +75 -0
  5. package/collection/bundles/blender-3d/skills/blender-asset/scripts/record_run.py +175 -0
  6. package/collection/bundles/blender-3d/skills/blender-asset/scripts/task_state.py +199 -0
  7. package/collection/bundles/blender-3d/skills/blender-asset/workflows/asset.yml +105 -0
  8. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/SKILL.md +115 -0
  9. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/check_motion.py +244 -0
  10. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/export_gltf_clip.py +71 -0
  11. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/godot_verify.py +87 -0
  12. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/inspect_motion_source.py +107 -0
  13. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/render_frames.py +117 -0
  14. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/verify_gltf.py +117 -0
  15. package/collection/bundles/blender-3d/skills/blender-reference-model/SKILL.md +110 -0
  16. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/colors.py +50 -0
  17. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/compare.py +77 -0
  18. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/contact_sheet.py +51 -0
  19. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/diff_renders.py +58 -0
  20. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/edges.py +54 -0
  21. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/measure_ref.py +137 -0
  22. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/mesh_report.py +67 -0
  23. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/refspec.py +91 -0
  24. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/render_views.py +99 -0
  25. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/zoom.py +47 -0
  26. package/collection/bundles/kit-adopt/README.md +1 -1
  27. package/collection/bundles/kit-adopt/skills/kit-adopt/SKILL.md +2 -2
  28. package/collection/bundles/session-retro/README.md +64 -0
  29. package/collection/bundles/session-retro/agents/retro-analyst.md +77 -0
  30. package/collection/bundles/session-retro/skills/session-retro/SKILL.md +74 -0
  31. package/collection/bundles/session-retro/skills/session-retro/scripts/install_hooks.py +114 -0
  32. package/collection/bundles/session-retro/skills/session-retro/scripts/retro_hook.py +117 -0
  33. package/collection/bundles/session-retro/skills/session-retro/scripts/session_digest.py +457 -0
  34. package/dist/agent-format.js +218 -0
  35. package/dist/catalog.js +13 -13
  36. package/dist/cli.js +95 -4
  37. package/dist/commands/adopt.js +13 -3
  38. package/dist/commands/ingest.js +120 -0
  39. package/dist/commands/sync.js +201 -0
  40. package/dist/commands/update.js +36 -0
  41. package/dist/portability.js +19 -2
  42. package/dist/providers.js +12 -2
  43. package/package.json +1 -1
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ """Explicit, consumer-local Blender task state; Python standard library only.
3
+
4
+ All reference paths are relative to the state file's directory, never the CWD.
5
+ Evidence stores SHA-256 of its declared inputs and the acceptance references.
6
+ Only changed dependencies invalidate a check. Run --help for the small CLI.
7
+ """
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import sys
15
+ import tempfile
16
+
17
+
18
+ PROFILES = {"quick": 1, "standard": 2, "production": 3}
19
+ RESULTS = ("pass", "fail", "not_tested")
20
+
21
+
22
+ def natural(value):
23
+ try:
24
+ number = int(value)
25
+ except ValueError:
26
+ raise argparse.ArgumentTypeError("expected a nonnegative integer")
27
+ if number < 0 or str(number) != value:
28
+ raise argparse.ArgumentTypeError("expected a nonnegative integer")
29
+ return number
30
+
31
+
32
+ def ref(base, value):
33
+ if not value.strip():
34
+ raise ValueError("reference paths must not be empty")
35
+ path = Path(value)
36
+ path = path if path.is_absolute() else base / path
37
+ return os.path.relpath(path.resolve(), base)
38
+
39
+
40
+ def digest(base, value):
41
+ path = base / value
42
+ if not path.is_file():
43
+ return None
44
+ hasher = hashlib.sha256()
45
+ with path.open("rb") as stream:
46
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
47
+ hasher.update(chunk)
48
+ return hasher.hexdigest()
49
+
50
+
51
+ def write_state(path, state, create=False):
52
+ payload = json.dumps(state, indent=2, allow_nan=False) + "\n"
53
+ path.parent.mkdir(parents=True, exist_ok=True)
54
+ if create:
55
+ with path.open("x", encoding="utf-8") as stream:
56
+ stream.write(payload)
57
+ stream.flush()
58
+ os.fsync(stream.fileno())
59
+ return
60
+ name = None
61
+ try:
62
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent,
63
+ prefix=".task-state-", delete=False) as stream:
64
+ name = stream.name
65
+ stream.write(payload)
66
+ stream.flush()
67
+ os.fsync(stream.fileno())
68
+ os.replace(name, path)
69
+ finally:
70
+ if name and os.path.exists(name):
71
+ os.unlink(name)
72
+
73
+
74
+ def read_state(path):
75
+ state = json.loads(path.read_text(encoding="utf-8"))
76
+ if (not isinstance(state, dict) or state.get("schema_version") != 1
77
+ or state.get("profile") not in PROFILES
78
+ or not isinstance(state.get("evidence"), dict)
79
+ or not isinstance(state.get("handoffs"), dict)
80
+ or not all(isinstance(state.get(key), list)
81
+ for key in ("artifacts", "acceptance_refs", "required", "repairs"))
82
+ or type(state.get("max_repairs")) is not int or state["max_repairs"] < 0):
83
+ raise ValueError("invalid task state schema")
84
+ return state
85
+
86
+
87
+ def nonempty(value):
88
+ if not value.strip():
89
+ raise argparse.ArgumentTypeError("value must not be empty")
90
+ return value
91
+
92
+
93
+ def status(state, base):
94
+ checks = {}
95
+ for name in sorted(set(state["required"]) | set(state["evidence"])):
96
+ record = state["evidence"].get(name)
97
+ reasons = []
98
+ if record is None:
99
+ result = "not_tested"
100
+ reasons.append("missing evidence")
101
+ else:
102
+ result = record["result"]
103
+ for dependency in record["dependencies"]:
104
+ actual = digest(base, dependency["path"])
105
+ if actual is None:
106
+ reasons.append("missing: " + dependency["path"])
107
+ elif actual != dependency["sha256"]:
108
+ reasons.append("changed: " + dependency["path"])
109
+ checks[name] = {"result": result, "valid": not reasons, "reasons": reasons,
110
+ "required": name in state["required"]}
111
+ missing_refs = [value for value in state["artifacts"] + state["acceptance_refs"]
112
+ if digest(base, value) is None]
113
+ considered = state["required"]
114
+ accepted = bool(considered) and not missing_refs and all(
115
+ checks[name]["valid"] and checks[name]["result"] == "pass" for name in considered)
116
+ failed = any(checks[name]["result"] == "fail" for name in considered)
117
+ return {"profile": state["profile"], "acceptance": "pass" if accepted else
118
+ ("fail" if failed else "not_tested"), "checks": checks,
119
+ "missing_refs": missing_refs, "repairs_used": len(state["repairs"]),
120
+ "max_repairs": state["max_repairs"],
121
+ "repairs_remaining": max(0, state["max_repairs"] - len(state["repairs"])),
122
+ "handoffs": state["handoffs"]}, accepted
123
+
124
+
125
+ def main():
126
+ parser = argparse.ArgumentParser(description=__doc__)
127
+ commands = parser.add_subparsers(dest="command", required=True)
128
+ init = commands.add_parser("init", help="create state; refuses an existing file")
129
+ init.add_argument("--profile", choices=PROFILES, default="standard")
130
+ init.add_argument("--artifact", action="append", default=[])
131
+ init.add_argument("--acceptance", action="append", default=[])
132
+ init.add_argument("--require", action="append", type=nonempty, default=[])
133
+ init.add_argument("--max-repairs", type=natural)
134
+ evidence = commands.add_parser("evidence", help="record a check and its content dependencies")
135
+ evidence.add_argument("--name", required=True, type=nonempty)
136
+ evidence.add_argument("--result", required=True, choices=RESULTS)
137
+ evidence.add_argument("--depends", action="append", default=[])
138
+ evidence.add_argument("--report")
139
+ evidence.add_argument("--note", default="")
140
+ inspect = commands.add_parser("status", help="diagnostic JSON status")
141
+ inspect.add_argument("--strict", action="store_true", help="exit 1 unless required checks pass; optional checks never block")
142
+ repair = commands.add_parser("repair", help="consume one repair round before doing the work")
143
+ repair.add_argument("--reason", required=True, type=nonempty)
144
+ handoff = commands.add_parser("handoff", help="persist separate compact build/fix handoffs")
145
+ handoff.add_argument("--phase", required=True, choices=("build", "fix"))
146
+ handoff.add_argument("--summary", required=True, type=nonempty)
147
+ handoff.add_argument("--next", action="append", type=nonempty, default=[])
148
+ handoff.add_argument("--ref", action="append", default=[])
149
+ for command in (init, evidence, inspect, repair, handoff):
150
+ command.add_argument("--state", type=Path, required=True)
151
+ args = parser.parse_args()
152
+ path = args.state.resolve()
153
+ base = path.parent
154
+ try:
155
+ if args.command == "init":
156
+ state = {"schema_version": 1, "profile": args.profile,
157
+ "artifacts": list(dict.fromkeys(ref(base, p) for p in args.artifact)),
158
+ "acceptance_refs": list(dict.fromkeys(ref(base, p) for p in args.acceptance)),
159
+ "required": list(dict.fromkeys(args.require)), "evidence": {},
160
+ "max_repairs": args.max_repairs if args.max_repairs is not None
161
+ else PROFILES[args.profile], "repairs": [],
162
+ "handoffs": {"build": None, "fix": None}}
163
+ write_state(path, state, create=True)
164
+ else:
165
+ state = read_state(path)
166
+ if args.command == "status":
167
+ report, accepted = status(state, base)
168
+ print(json.dumps(report, allow_nan=False))
169
+ return 1 if args.strict and not accepted else 0
170
+ if args.command == "evidence":
171
+ paths = [ref(base, p) for p in args.depends] + state["acceptance_refs"]
172
+ if args.report:
173
+ paths.append(ref(base, args.report))
174
+ paths = list(dict.fromkeys(paths))
175
+ if args.result != "not_tested" and not paths:
176
+ raise ValueError("pass/fail evidence needs at least one --depends, --report, or acceptance reference")
177
+ dependencies = [{"path": p, "sha256": digest(base, p)} for p in paths]
178
+ if args.result != "not_tested" and any(d["sha256"] is None for d in dependencies):
179
+ raise ValueError("pass/fail evidence dependencies must be existing regular files")
180
+ state["evidence"][args.name] = {"result": args.result, "dependencies": dependencies,
181
+ "report": ref(base, args.report) if args.report else None,
182
+ "note": args.note}
183
+ elif args.command == "repair":
184
+ if len(state["repairs"]) >= state["max_repairs"]:
185
+ raise ValueError("repair limit reached; stop and report the remaining failure")
186
+ state["repairs"].append({"round": len(state["repairs"]) + 1, "reason": args.reason})
187
+ elif args.command == "handoff":
188
+ state["handoffs"][args.phase] = {"summary": args.summary, "next": args.next,
189
+ "refs": [ref(base, p) for p in args.ref]}
190
+ write_state(path, state)
191
+ print(json.dumps(state, allow_nan=False))
192
+ return 0
193
+ except (OSError, ValueError, KeyError, TypeError) as error:
194
+ print("task_state: " + str(error), file=sys.stderr)
195
+ return 2
196
+
197
+
198
+ if __name__ == "__main__":
199
+ sys.exit(main())
@@ -0,0 +1,105 @@
1
+ # Declarative instructions for the calling agent/manager; not executable automation.
2
+ version: 1
3
+ name: blender-asset
4
+ purpose: Choose the smallest workflow that meets the task's acceptance criteria.
5
+ entry: blender-asset
6
+ contract:
7
+ required:
8
+ - brief and authoritative input/output paths
9
+ - profile with reason and measurable acceptance criteria
10
+ - required evidence IDs, views/checks and task-specific tolerances
11
+ - allowed changes, units/axes/origin and deliverables
12
+ optional:
13
+ - reference priority and intentional deviations
14
+ - source motion, root-motion mode and expected clip names
15
+ - target engine, intended gameplay size and deformation constraints
16
+ - local model/effort preset and usage/render budget
17
+ selection:
18
+ owner: calling agent or manager
19
+ rules:
20
+ - Honor an explicitly requested profile; never silently weaken its required gates.
21
+ - Choose quick for a simple prop, prototype, material/origin edit or isolated repair.
22
+ - Choose standard for reference matching, modular assets or ordinary game-ready delivery.
23
+ - Choose production for strict fidelity, complex assemblies, critical deformation or dependent deliverables.
24
+ - Classify by acceptance risk and dependencies, not polygon count alone.
25
+ - Record the choice briefly; only ask about a missing decision that changes acceptance.
26
+ profiles:
27
+ quick:
28
+ stages: [contract, build, technical_checks, affected_views, conditional_review, delivery]
29
+ reviewer: optional_only_when_requested_or_material_uncertainty
30
+ max_repairs: 1
31
+ standard:
32
+ stages: [contract, proportions, build, reference_comparison_if_applicable, technical_checks, conditional_review, delivery]
33
+ reviewer: required_when_requested_or_identity_or_acceptance_remains_uncertain
34
+ max_repairs: 2
35
+ production:
36
+ stages: [contract, blockout_checkpoint, refine, technical_checks, independent_review, delivery]
37
+ reviewer: required
38
+ max_repairs: 3
39
+ stage_owners:
40
+ contract: calling agent records criteria, required evidence IDs and repair limit before building
41
+ proportions: builder establishes dimensions and primary forms before detail
42
+ blockout_checkpoint: compare primary forms to acceptance; resolve material ambiguity before refining
43
+ build: blender-asset, or blender-reference-model when matching a supplied reference
44
+ refine: same builder capability with the accepted blockout and scoped changes
45
+ technical_checks: builder runs only the contract's relevant geometry, material, motion and export checks
46
+ reference_comparison_if_applicable: blender-reference-model produces matched views and identity-detail evidence
47
+ affected_views: builder renders only views needed to judge the changed region and its dependencies
48
+ conditional_review: visual-reviewer if the profile's condition holds; otherwise record why unnecessary
49
+ independent_review: visual-reviewer receives a compact evidence packet in a fresh context
50
+ delivery: calling agent evaluates every required criterion against current evidence
51
+ capability_additions:
52
+ reference:
53
+ when: task requires fidelity to a supplied reference
54
+ capability: blender-reference-model
55
+ rule: Supply view priorities and tolerances; no universal silhouette IoU target.
56
+ motion:
57
+ when: task rigs or retargets existing source motion onto an existing character
58
+ capability: blender-mocap-retarget
59
+ rule: Preserve the authoritative model; add source comparison, rest-pose identity and motion checks without restarting modeling.
60
+ export:
61
+ when: task requests an interchange or engine-ready deliverable
62
+ tools: blender-mocap-retarget/scripts/verify_gltf.py; godot_verify.py only for a Godot target
63
+ rule: Declare expected clip set and required geometry/skin/rig; re-import the exported artifact and run target checks when required.
64
+ review:
65
+ default_team: none
66
+ production_reviewers: 1
67
+ packet:
68
+ - brief, priorities, intentional deviations and acceptance criteria
69
+ - reference/source images when relevant, current evidence and intended display size
70
+ - changed regions, unresolved findings and missing views/checks
71
+ rules:
72
+ - Do not send full session transcripts, repeated skill text or builder code.
73
+ - If image viewing or an independent agent is unavailable, record review as not_tested.
74
+ - A required review that cannot run blocks acceptance; deliver partial progress and identify the missing capability.
75
+ - A Quick or Standard reviewer trigger adds a gate without automatically escalating the entire profile.
76
+ repair:
77
+ owner: calling agent
78
+ rules:
79
+ - Initialize task_state.py with the profile limit before building and reserve each repair before starting it.
80
+ - Each repair targets the highest-priority unmet criteria; preserve successful work.
81
+ - A separate fix session resumes from task state, asset/script paths and current findings, not the full transcript.
82
+ - Reuse evidence only if all its declared input dependencies still match; hashes cannot infer omitted dependencies.
83
+ - After a change, rerun affected checks and views, including required reviewer findings affected by the change.
84
+ - Include asset, script, task contract, references, render settings and export inputs as appropriate dependencies.
85
+ - If a repair makes no material progress or the limit is exhausted, stop repairing and report remaining defects with a scoped next step.
86
+ - Never reset task state or raise a limit silently to continue; a further work budget requires a user decision.
87
+ - Escalate profile only when new acceptance risk requires it; retain valid evidence and consumed rounds.
88
+ usage:
89
+ rules:
90
+ - The coordinator is the sole writer of task state and usage journals; serialize writes and collect child metrics instead of concurrent appends.
91
+ - Record separate create, review, fix and delivery phases with model, effort and parent/child call identity when available.
92
+ - Record own per-call usage only; do not add child usage to an already inclusive parent total.
93
+ - Record tokens, API/tool calls, render count/time and acceptance; unknown metrics remain null, never zero.
94
+ - Treat cost estimates as advisory unless complete live metering exists; report coverage and price source.
95
+ - Stop new work when a declared measurable render/time/token budget is exhausted; report remaining criteria and request a revised budget.
96
+ - When a required hard budget cannot be metered, report that limitation before proceeding under it; do not infer room from unknown usage.
97
+ - Select model and effort from consumer configuration; do not assume a cheaper model achieves equal quality.
98
+ - Prefer one builder and bounded fixes; delegate only independent work likely to justify its context and review cost.
99
+ completion:
100
+ rules:
101
+ - All required checks and reviews must pass with current evidence; not_tested or stale evidence blocks acceptance.
102
+ - Visual approval cannot replace a technical or engine gate; technical pass cannot replace required visual review.
103
+ - Optional defects and untested optional capabilities are disclosed without forcing extra rounds.
104
+ - Deliver editable source, persisted scripts, requested exports, evidence summary and measured usage coverage.
105
+ - Record outcome as accepted, partial or blocked; never claim savings without comparable accepted-task measurements.
@@ -0,0 +1,115 @@
1
+ ---
2
+ name: blender-mocap-retarget
3
+ description: Rig, skin and retarget an existing motion-capture or library clip (for example Mixamo FBX) onto an existing Blender character without changing the character, then verify and export it for a game engine. Use when adding source animation to a finished model; not for modeling, and not for hand-keyed animation from scratch.
4
+ ---
5
+
6
+ # Blender Mocap Retarget
7
+
8
+ ## Scope
9
+
10
+ Rig, skin and retarget source motion onto an existing character while preserving its appearance.
11
+ Work to the task's motion, root displacement, loop and delivery criteria. Profile selection,
12
+ independent review and bounded repairs are owned by `../blender-asset/workflows/asset.yml`;
13
+ adding animation does not require restarting the modeling workflow.
14
+
15
+ ## Prerequisites
16
+
17
+ - Install the complete `blender-3d` bundle; its sibling skills and workflow are required context.
18
+ - Install [Blender](https://www.blender.org/download/); verify `blender --version`.
19
+ - Install [Python 3](https://www.python.org/downloads/) and `python3 -m pip install Pillow numpy`
20
+ for sibling [Pillow](https://pillow.readthedocs.io/) / [NumPy](https://numpy.org/) image helpers; verify `python3 -c "import PIL, numpy"`.
21
+ - Only for a required Godot check: install [Godot 4](https://godotengine.org/download/) and
22
+ verify `godot --version`; set `GODOT` if the executable is not on `PATH`.
23
+ - Resolve script paths from their skill directories; keep executable paths in consumer config.
24
+
25
+ ## Invariants
26
+
27
+ - Do not remodel. The rest pose must render identically to the unrigged model: render
28
+ baseline views before rigging and diff them against rest-pose renders afterwards. If deformation truly needs geometry (for example extra loops at joints), add it
29
+ without changing the rest-pose renders, and show the diff.
30
+ - Build the armature on the character's own joints. Never stretch the character to the source
31
+ skeleton; absorb differences in the retarget.
32
+ - Modular objects stay separate. Each deforming part gets its own Armature modifier; rigid
33
+ equipment follows one bone (or a socket bone) with full weight.
34
+ - Keep the source clip, and any imported source rig, out of the export: use a separate hidden
35
+ collection or a separate file.
36
+ - Use a persisted script for rig, weights and retarget, so the result can be rebuilt.
37
+
38
+ ## Tools
39
+
40
+ Scripts in this skill's `scripts/` folder (Blender scripts run with `blender -b ... --python`):
41
+
42
+ | Script | Purpose |
43
+ | --- | --- |
44
+ | `inspect_motion_source.py` | Skeleton, fps, frame range, rest pose, root motion, foot height offset, loop seam of the source |
45
+ | `check_motion.py` | Ground penetration, planted-foot slide, interpenetration beyond the rest baseline, loop seam |
46
+ | `render_frames.py` | Frame renders from several angles with following cameras and a checker floor |
47
+ | `export_gltf_clip.py` | GLB export with exactly one clip per named action |
48
+ | `verify_gltf.py` | Re-import; check requested mesh/skin/rig requirements and clip timing; `--exact-clips` rejects extra or missing original clip names |
49
+ | `godot_verify.py` | Optional: headless Godot import of the GLB, checking meshes, bones, clips and key timing |
50
+
51
+ The sibling skill's scripts are used too, at `../blender-reference-model/scripts/` relative to
52
+ this skill's folder (not the working directory): `render_views.py` and `diff_renders.py` for the
53
+ rest-pose check, and `contact_sheet.py` to tile frame renders.
54
+
55
+ ## Procedure
56
+
57
+ Apply Stop Conditions immediately during every step; return the blocked work and evidence gaps.
58
+
59
+ 1. Capture baseline views with the character's spec (or a spec that frames the asset), using
60
+ reproducible render settings. Identify authoritative asset, source clip, output and allowed edits.
61
+ 2. Inspect source fps, range, rest pose, root motion and loop structure. Select and record root
62
+ motion deliberately: preserve source distance, scale proportionally, or make in-place.
63
+ Do not change the requested displacement merely to hide foot slide.
64
+ 3. Build the rig on the character's joints and retarget rest-relative rotations. Account for
65
+ source offsets and scale. Use foot constraints/IK only as needed; compare source and target
66
+ at aligned phase/time, including a non-looping end when relevant.
67
+ 4. Skin deforming regions with appropriate blend zones; bind rigid attachments to their intended
68
+ bones/sockets. Correct observed collisions with the smallest local adjustment. Outward arm
69
+ offsets, clavicle damping and prop swing are optional measured corrections, never defaults;
70
+ preserve source performance and verify each correction against it.
71
+ 5. Repeat the baseline rest-pose renders with identical settings and run `diff_renders.py`.
72
+ A difference outside the agreed tolerance fails appearance preservation.
73
+ 6. Run `check_motion.py` on named feet, pairs and frame range. Record coverage and statuses.
74
+ Choose task-specific ground, planted-slide, overlap and loop tolerances; do not apply walking
75
+ or looping criteria to a jump or non-looping clip. Strict mode needs at least one threshold
76
+ and fails unmet thresholds or missing requested coverage. Run with `--python-exit-code 1`.
77
+ 7. Inspect affected frame contact sheets at the intended size, including representative contacts,
78
+ transitions and extremes. Missing views cannot prove motion continuity; report sampling limits.
79
+ 8. For requested exports, isolate intended actions and export. Use `verify_gltf.py` with
80
+ `--expect-clips Walk,Run --exact-clips` (substitute the contract's exact names) and the required
81
+ `--require-mesh`, `--require-skin`, `--require-rig` flags. For a static export the expected clip
82
+ set is empty. Run target-engine checks when required by the contract.
83
+ 9. Return motion evidence and unresolved defects after this stage. The companion workflow
84
+ decides review and any further reserved repair; it does not require fresh modeling.
85
+
86
+ ## Stop Conditions
87
+
88
+ Missing authoritative assets/source, conflicting displacement requirements, or a required
89
+ appearance-changing edit outside scope blocks the affected work. Mark missing tool/check
90
+ coverage `not_tested`; never claim delivery acceptance with a missing required check or review.
91
+
92
+ ## Known Pitfalls
93
+
94
+ - Blender 5.x stores animation in layered actions. F-curves live under
95
+ `action.layers[].strips[].channelbags[].fcurves`; `action.fcurves` no longer lists them.
96
+ - Mixamo FBX armatures import with object scale 0.01, and a walk's feet can sit above the rest
97
+ pose (about 1.4 cm in Mixamo's Walking). Subtract that offset before scaling, or feet float.
98
+ - Exported clip time counts from scene frame 0, so an action that starts at frame 1 arrives
99
+ offset by one frame. Put each action on its own NLA track, named after the clip, with the
100
+ strip at frame 0, and export in `NLA_TRACKS` mode. Confirm the first key is at time 0 with
101
+ `verify_gltf.py` or `godot_verify.py`. In the sessions this came from, `ACTIVE_ACTIONS` named
102
+ the clip "Animation" and `ACTIONS` also exported stray source actions.
103
+ - For a loop whose last frame repeats the first plus one stride, set the scene range to exclude
104
+ the repeated frame, so playback does not stutter.
105
+ - Overlap tests between adjacent regions of one mesh report shared edges. Pair regions that
106
+ should never touch.
107
+
108
+ ## Output Contract
109
+
110
+ `Skill: blender-mocap-retarget - output below`
111
+
112
+ Report source facts and root-motion mode; editable asset and persisted script; rest-pose diff;
113
+ motion-check statuses, thresholds and sampled frames/objects; source/target contact sheets;
114
+ requested export/engine verification; unresolved defects and missing evidence. Distinguish
115
+ technical pass from visual judgment and engine checks that have not run.
@@ -0,0 +1,244 @@
1
+ """Per-frame motion QA for a rigged, animated character (read-only).
2
+
3
+ blender -b model.blend --python check_motion.py -- --rig Armature \
4
+ --feet Boot_L,Boot_R --pairs "Shirt@LeftForeArm:Belt;Shirt@RightForeArm:Pouch_R;Boot_L:Boot_R" [--json qa.json]
5
+
6
+ Checks over the scene frame range (or --frames A-B):
7
+ - ground: lowest point of each --feet part per frame; below -tolerance is penetration
8
+ - slide: horizontal travel of foot vertices that stay in floor contact between frames
9
+ - interpenetration: overlapping triangles per --pairs entry, minus the count already present
10
+ in the rest pose (bridged seams and tucked cloth are not motion errors)
11
+ - loop seam: rotation difference between the action's first and last frame, and root delta
12
+
13
+ Neighbouring regions of one mesh share edges, and deforming them can register as overlap; pair
14
+ regions that should never touch (arm vs belt kit, arm vs torso front) rather than adjacent ones.
15
+ A part is an object name, optionally narrowed to polygons whose dominant vertex group contains a
16
+ substring: "Shirt@LeftArm" = Shirt polygons weighted mostly to a group containing "LeftArm".
17
+ Judge motion quality from playback renders too; these numbers catch regressions, not style.
18
+
19
+ Use --strict with one or more task-defined --max-ground-penetration-mm,
20
+ --max-planted-slide-mm-per-frame, --max-extra-overlap-tris, or --max-loop-rotation-deg
21
+ thresholds to fail violations and missing requested coverage. Without --strict, diagnostic
22
+ exit behavior is preserved. JSON checks distinguish measured coverage from acceptance:
23
+ no threshold or missing samples is not_tested, never a passing acceptance decision.
24
+ Pass Blender --python-exit-code 1 before --python to propagate Python failures.
25
+ """
26
+ import argparse
27
+ import json
28
+ import math
29
+ import re
30
+ import sys
31
+
32
+ import bpy
33
+ from mathutils.bvhtree import BVHTree
34
+
35
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
36
+
37
+
38
+ def finite(value):
39
+ number = float(value)
40
+ if not math.isfinite(number):
41
+ raise argparse.ArgumentTypeError("must be finite")
42
+ return number
43
+
44
+
45
+ def nonnegative(value):
46
+ number = finite(value)
47
+ if number < 0:
48
+ raise argparse.ArgumentTypeError("must be nonnegative")
49
+ return number
50
+
51
+
52
+ p = argparse.ArgumentParser()
53
+ p.add_argument("--rig", required=True)
54
+ p.add_argument("--feet", default="", help="comma-separated parts that touch the floor")
55
+ p.add_argument("--pairs", default="", help="semicolon-separated A:B part pairs to test for overlap")
56
+ p.add_argument("--frames", help="START-END; default is the scene range")
57
+ p.add_argument("--contact-mm", type=nonnegative, default=6.0, help="height that counts as floor contact")
58
+ p.add_argument("--ground-z", type=finite, default=0.0)
59
+ p.add_argument("--strict", action="store_true", help="fail requested thresholds when exceeded or untested; requires at least one threshold")
60
+ p.add_argument("--max-ground-penetration-mm", type=nonnegative)
61
+ p.add_argument("--max-planted-slide-mm-per-frame", type=nonnegative)
62
+ p.add_argument("--max-extra-overlap-tris", type=nonnegative)
63
+ p.add_argument("--max-loop-rotation-deg", type=nonnegative)
64
+ p.add_argument("--json")
65
+ args = p.parse_args(argv)
66
+
67
+ scene = bpy.context.scene
68
+ rig = bpy.data.objects.get(args.rig)
69
+ if rig is None or rig.type != "ARMATURE":
70
+ raise SystemExit(f"--rig: no armature object named {args.rig}")
71
+ if args.frames:
72
+ match = re.fullmatch(r"(-?\d+)-(-?\d+)", args.frames)
73
+ if not match:
74
+ p.error("--frames must be START-END with integer frames")
75
+ f0, f1 = map(int, match.groups())
76
+ else:
77
+ f0, f1 = scene.frame_start, scene.frame_end
78
+ if f1 < f0:
79
+ p.error("--frames end must be at least start")
80
+ frame_property = scene.bl_rna.properties["frame_current"]
81
+ if f0 < frame_property.hard_min or f1 > frame_property.hard_max:
82
+ p.error(f"--frames must be within Blender's range {frame_property.hard_min:g}-{frame_property.hard_max:g}")
83
+ feet = [s for s in args.feet.split(",") if s]
84
+ pairs = [tuple(pair.split(":")) for pair in args.pairs.split(";") if pair]
85
+ if any(len(pair) != 2 or not all(pair) for pair in pairs):
86
+ p.error("--pairs must contain A:B entries separated by semicolons")
87
+ contact = args.contact_mm / 1000.0
88
+
89
+
90
+ def parse(part):
91
+ name, _, group = part.partition("@")
92
+ ob = bpy.data.objects.get(name)
93
+ if ob is None or ob.type != "MESH":
94
+ raise SystemExit(f"no mesh object named {name}")
95
+ return ob, group
96
+
97
+
98
+ def select_polys(ob, group):
99
+ me = ob.data
100
+ if not group:
101
+ chosen = [list(poly.vertices) for poly in me.polygons]
102
+ if not chosen:
103
+ raise SystemExit(f"no polygons in {ob.name}")
104
+ return chosen
105
+ names = {g.index: g.name for g in ob.vertex_groups}
106
+ chosen = []
107
+ for poly in me.polygons:
108
+ acc = {}
109
+ for vi in poly.vertices:
110
+ for g in me.vertices[vi].groups:
111
+ acc[g.group] = acc.get(g.group, 0.0) + g.weight
112
+ if acc and group in names.get(max(acc, key=acc.get), ""):
113
+ chosen.append(list(poly.vertices))
114
+ if not chosen:
115
+ raise SystemExit(f"no polygons of {ob.name} are dominated by a group containing '{group}'")
116
+ return chosen
117
+
118
+
119
+ parts = sorted({p for pair in pairs for p in pair} | set(feet))
120
+ POLYS = {part: select_polys(*parse(part)) for part in parts}
121
+
122
+
123
+ def evaluate():
124
+ dg = bpy.context.evaluated_depsgraph_get()
125
+ verts = {}
126
+ for part in parts:
127
+ ob, _ = parse(part)
128
+ if ob.name in verts:
129
+ continue
130
+ ev = ob.evaluated_get(dg)
131
+ me = ev.to_mesh()
132
+ if len(me.vertices) != len(ob.data.vertices):
133
+ raise SystemExit(f"{ob.name}: modifiers change the vertex count; check_motion needs only deforming modifiers (Armature)")
134
+ verts[ob.name] = [ob.matrix_world @ v.co for v in me.vertices]
135
+ ev.to_mesh_clear()
136
+ return verts
137
+
138
+
139
+ def overlaps(verts):
140
+ trees = {part: BVHTree.FromPolygons(verts[parse(part)[0].name], POLYS[part]) for part in {p for pair in pairs for p in pair}}
141
+ return {pair: len(trees[pair[0]].overlap(trees[pair[1]])) for pair in pairs}
142
+
143
+
144
+ rig.data.pose_position = "REST"
145
+ scene.frame_set(f0)
146
+ baseline = overlaps(evaluate())
147
+ rig.data.pose_position = "POSE"
148
+
149
+ ground, slide, hits = {f: [] for f in feet}, {f: [] for f in feet}, {pair: [] for pair in pairs}
150
+ prev = {}
151
+ for frame in range(f0, f1 + 1):
152
+ scene.frame_set(frame)
153
+ verts = evaluate()
154
+ for pair, n in overlaps(verts).items():
155
+ extra = n - baseline[pair]
156
+ if extra > 0:
157
+ hits[pair].append((frame, extra))
158
+ for foot in feet:
159
+ ob, _ = parse(foot)
160
+ idx = sorted({i for poly in POLYS[foot] for i in poly})
161
+ co = [verts[ob.name][i] for i in idx]
162
+ low = min(c.z for c in co) - args.ground_z
163
+ ground[foot].append((frame, low))
164
+ touching = {i for i, c in zip(idx, co) if c.z - args.ground_z < contact}
165
+ if foot in prev:
166
+ both = touching & prev[foot][1]
167
+ if both:
168
+ pc = prev[foot][0]
169
+ slide[foot].append((frame, max((verts[ob.name][i].xy - pc[i].xy).length for i in both)))
170
+ prev[foot] = (verts[ob.name], touching)
171
+
172
+ report = {"frames": [f0, f1], "ground": {}, "slide": {}, "interpenetration": {}, "rest_baseline_overlaps": {}}
173
+ for foot in feet:
174
+ lows = [z for _, z in ground[foot]]
175
+ report["ground"][foot] = {"min_mm": round(min(lows) * 1000, 1), "contact_frames": sum(z < contact for z in lows)}
176
+ if slide[foot]:
177
+ vals = [v for _, v in slide[foot]]
178
+ worst = max(slide[foot], key=lambda fv: fv[1])
179
+ report["slide"][foot] = {"max_mm_per_frame": round(worst[1] * 1000, 1), "worst_frame": worst[0],
180
+ "mean_mm_per_frame": round(sum(vals) / len(vals) * 1000, 1)}
181
+ for pair in pairs:
182
+ key = f"{pair[0]} x {pair[1]}"
183
+ report["rest_baseline_overlaps"][key] = baseline[pair]
184
+ if hits[pair]:
185
+ report["interpenetration"][key] = {"frames": len(hits[pair]), "max_extra_tris": max(n for _, n in hits[pair]),
186
+ "first_frames": [f for f, _ in hits[pair]][:12]}
187
+
188
+ act = rig.animation_data.action if rig.animation_data else None
189
+ loop_rotation = None
190
+ if act and rig.pose.bones and act.frame_range[1] > act.frame_range[0]:
191
+ a0, a1 = (float(v) for v in act.frame_range)
192
+
193
+ def pose(frame):
194
+ whole_frame = math.floor(frame)
195
+ scene.frame_set(whole_frame, subframe=frame - whole_frame)
196
+ return {pb.name: (pb.matrix_basis.to_quaternion(), pb.matrix_basis.to_translation()) for pb in rig.pose.bones}
197
+
198
+ pa, pb_ = pose(a0), pose(a1)
199
+ worst = max(pa, key=lambda n: pa[n][0].rotation_difference(pb_[n][0]).angle)
200
+ root = next(b.name for b in rig.data.bones if b.parent is None)
201
+ loop_rotation = math.degrees(pa[worst][0].rotation_difference(pb_[worst][0]).angle)
202
+ report["loop_seam"] = {"action": act.name, "action_range": [a0, a1],
203
+ "max_rotation_diff_deg": round(loop_rotation, 3),
204
+ "worst_bone": worst, "root_bone": root,
205
+ "root_delta_bone_space_m": [round(v, 4) for v in (pb_[root][1] - pa[root][1])]}
206
+
207
+ # Keep legacy diagnostic metrics above. Decisions use full precision, not rounded display values.
208
+ # Slide coverage requires a contact transition for EVERY requested foot.
209
+ measurements = {
210
+ "ground": (args.max_ground_penetration_mm,
211
+ max((max(0.0, -z * 1000) for values in ground.values() for _, z in values), default=None),
212
+ bool(feet), "no feet supplied"),
213
+ "slide": (args.max_planted_slide_mm_per_frame,
214
+ max((v * 1000 for values in slide.values() for _, v in values), default=None),
215
+ bool(feet) and all(slide[foot] for foot in feet),
216
+ "no planted contact transitions for: " + ", ".join(foot for foot in feet if not slide[foot]) if feet else "no feet supplied"),
217
+ "interpenetration": (args.max_extra_overlap_tris,
218
+ max((n for values in hits.values() for _, n in values), default=0) if pairs else None,
219
+ bool(pairs), "no pairs supplied"),
220
+ "loop_seam": (args.max_loop_rotation_deg, loop_rotation, loop_rotation is not None,
221
+ "no active action spanning distinct frames with pose bones"),
222
+ }
223
+ report["checks"] = {}
224
+ for name, (threshold, observed, tested, reason) in measurements.items():
225
+ requested = threshold is not None
226
+ status = "not_tested" if not tested or not requested else ("pass" if observed <= threshold else "fail")
227
+ check = {"status": status, "tested": tested, "requested": requested, "threshold": threshold, "observed": observed}
228
+ if not tested:
229
+ check["reason"] = reason
230
+ elif not requested:
231
+ check["reason"] = "no acceptance threshold supplied"
232
+ report["checks"][name] = check
233
+ requested_checks = [check for check in report["checks"].values() if check["requested"]]
234
+ report["strict"] = args.strict
235
+ report["status"] = ("fail" if any(check["status"] == "fail" for check in requested_checks)
236
+ or (args.strict and (not requested_checks or any(check["status"] != "pass" for check in requested_checks)))
237
+ else "pass" if requested_checks and all(check["status"] == "pass" for check in requested_checks)
238
+ else "not_tested")
239
+
240
+ print(json.dumps(report, indent=2))
241
+ if args.json:
242
+ with open(args.json, "w") as f:
243
+ json.dump(report, f, indent=2)
244
+ sys.exit(1 if args.strict and report["status"] != "pass" else 0)