cozyclay 1.10.0 → 2.0.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 (272) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/bin/agent/agent-routes.mjs +74 -70
  3. package/bin/agent/agent-runner.mjs +10 -3
  4. package/bin/agent/motion-runtime.mjs +32 -260
  5. package/bin/agent/providers.mjs +46 -3
  6. package/bin/agent/session-store.mjs +41 -5
  7. package/bin/agent/studio-prompt.mjs +1 -1
  8. package/bin/agent/studio-tools.mjs +48 -11
  9. package/bin/cozyclay.mjs +26 -8
  10. package/bin/live/cli.mjs +22 -3
  11. package/bin/mcp-runtime.mjs +35 -20
  12. package/bin/telemetry-state.mjs +5 -2
  13. package/bin/update-check.mjs +15 -0
  14. package/dist/app/index.html +6 -6
  15. package/dist/assets/analytics-MVZOEW8O.js +1 -0
  16. package/dist/assets/app-C1sdVbg4.css +1 -0
  17. package/dist/assets/app-CA55tcI3.js +4876 -0
  18. package/dist/assets/{demo-B-eg1CT8.js → demo-ByeYp-dY.js} +1 -1
  19. package/dist/assets/{first-shot-handoff-CGgnvNu8.js → first-shot-handoff-DgT28ZiV.js} +1 -1
  20. package/dist/assets/{landing-IbRp3FnQ.js → landing-BaXkpFip.js} +1 -1
  21. package/dist/assets/shot-prompt-CbqWcWYi.css +1 -0
  22. package/dist/assets/shot-prompt-Yrt99wZx.js +17 -0
  23. package/dist/assets/{ticket-BgIzOBOf.js → ticket-BcmsnHn5.js} +1 -1
  24. package/dist/assets/workflow-DRdwoDBT.css +1 -0
  25. package/dist/assets/workflow-dNPGY9xz.js +179 -0
  26. package/dist/cozyclay-package.json +1 -1
  27. package/dist/fonts/IBM-Plex-Sans-OFL.txt +92 -0
  28. package/dist/fonts/JetBrains-Mono-OFL.txt +93 -0
  29. package/dist/fonts/README.md +13 -9
  30. package/dist/fonts/ibm-plex-sans-400-latin.woff2 +0 -0
  31. package/dist/fonts/ibm-plex-sans-500-latin.woff2 +0 -0
  32. package/dist/fonts/ibm-plex-sans-600-latin.woff2 +0 -0
  33. package/dist/fonts/jetbrains-mono-400-latin.woff2 +0 -0
  34. package/dist/fonts/jetbrains-mono-500-latin.woff2 +0 -0
  35. package/dist/index.html +7 -7
  36. package/dist/privacy/index.html +13 -8
  37. package/dist/sitemap.xml +6 -6
  38. package/dist/workflow/index.html +5 -5
  39. package/mcp/live-hub.mjs +35 -93
  40. package/mcp/mesh-file.mjs +48 -0
  41. package/mcp/server.mjs +6 -77
  42. package/mcp/tool-handlers.mjs +219 -376
  43. package/package.json +2 -1
  44. package/src/App.jsx +1249 -9076
  45. package/src/analytics.js +393 -9
  46. package/src/app-context.js +211 -0
  47. package/src/app-stage.jsx +25 -24
  48. package/src/ardy/auto-fix-panel.css +108 -0
  49. package/src/ardy/fix-collisions.js +10 -66
  50. package/src/ardy/ik-drag.js +101 -0
  51. package/src/ardy/ik-key-json.js +43 -0
  52. package/src/ardy/ik.js +97 -67
  53. package/src/ardy/physics-panel.css +2 -0
  54. package/src/ardy/physics-panel.jsx +17 -5
  55. package/src/ardy/platform-fit-panel.css +64 -0
  56. package/src/ardy/platform-fit-panel.jsx +40 -0
  57. package/src/ardy/platform-fit.js +326 -0
  58. package/src/ardy/playback.js +166 -20
  59. package/src/ardy/range-pin.js +299 -0
  60. package/src/ardy/timeline-coordinates.js +26 -0
  61. package/src/ardy/timeline.css +1199 -0
  62. package/src/ardy/timeline.jsx +149 -41
  63. package/src/ardy/waypoints.js +2 -2
  64. package/src/asset-pane.css +462 -0
  65. package/src/asset-pane.jsx +461 -232
  66. package/src/command-bus.js +349 -0
  67. package/src/commands/ai.js +31 -0
  68. package/src/commands/cast.js +140 -0
  69. package/src/commands/elements/character.js +13 -0
  70. package/src/commands/elements/motion.js +14 -0
  71. package/src/commands/elements/object.js +22 -0
  72. package/src/commands/elements/scene.js +16 -0
  73. package/src/commands/elements/shot.js +9 -0
  74. package/src/commands/elements/stage.js +11 -0
  75. package/src/commands/elements.js +155 -0
  76. package/src/commands/export.js +20 -0
  77. package/src/commands/index.js +40 -0
  78. package/src/commands/motion.js +231 -0
  79. package/src/commands/objects.js +174 -0
  80. package/src/commands/project.js +53 -0
  81. package/src/commands/scene.js +81 -0
  82. package/src/commands/shared.js +19 -0
  83. package/src/commands/shot.js +103 -0
  84. package/src/commands/stage.js +17 -0
  85. package/src/commands/view.js +42 -0
  86. package/src/document-store.js +144 -0
  87. package/src/domains/cast.js +1007 -0
  88. package/src/domains/motion.js +3219 -0
  89. package/src/domains/objects.js +932 -0
  90. package/src/domains/scenes.js +817 -0
  91. package/src/domains/shots.js +404 -0
  92. package/src/domains/stage.js +93 -0
  93. package/src/dualview.jsx +113 -57
  94. package/src/facing-marks.js +3 -0
  95. package/src/first-success-guide.jsx +14 -14
  96. package/src/grid-view.js +18 -5
  97. package/src/hierarchy-panel.css +386 -0
  98. package/src/hierarchy-panel.jsx +88 -19
  99. package/src/{fal-motion-client.js → i2v-motion-client.js} +13 -13
  100. package/src/i2v-motion-studio.jsx +180 -0
  101. package/src/ik-camera.js +3 -0
  102. package/src/main.jsx +6 -0
  103. package/src/motion/generation.js +105 -0
  104. package/src/motion-readiness-ui.jsx +4 -4
  105. package/src/motion-readiness.js +11 -0
  106. package/src/motion-trail.js +366 -9
  107. package/src/object-gizmo.jsx +7 -1
  108. package/src/panels/CameraPanel.jsx +60 -0
  109. package/src/panels/CharacterTransformPanel.jsx +48 -0
  110. package/src/panels/EnvironmentPanel.jsx +40 -0
  111. package/src/panels/Foldout.jsx +32 -0
  112. package/src/panels/LightPanel.jsx +24 -0
  113. package/src/panels/ObjectTransformPanel.jsx +554 -0
  114. package/src/panels/PosePanel.jsx +97 -0
  115. package/src/panels/ProjectPanel.jsx +33 -0
  116. package/src/panels/PromptBlocksPanel.jsx +442 -0
  117. package/src/panels/PropsPanel.jsx +70 -0
  118. package/src/panels/ReferenceImageField.jsx +91 -0
  119. package/src/panels/RigControlPanel.jsx +78 -0
  120. package/src/panels/RigPanel.jsx +37 -0
  121. package/src/panels/SubjectBox.jsx +47 -0
  122. package/src/panels/SubjectsPanel.jsx +39 -0
  123. package/src/panels/VideoCapturePanel.jsx +180 -0
  124. package/src/panels/details.css +1171 -0
  125. package/src/panels/motion.css +197 -0
  126. package/src/panels/pose.css +39 -0
  127. package/src/planview.jsx +60 -31
  128. package/src/posestudio.jsx +59 -4
  129. package/src/project-browser.css +1073 -0
  130. package/src/project-browser.jsx +284 -123
  131. package/src/range-pin-object-transform.js +19 -0
  132. package/src/range-pin-panel.css +518 -0
  133. package/src/range-pin-panel.jsx +344 -0
  134. package/src/result-modal.jsx +5 -5
  135. package/src/room.jsx +79 -51
  136. package/src/scenes.js +5 -0
  137. package/src/semantic-edit.js +2 -0
  138. package/src/settings-menu.jsx +39 -105
  139. package/src/shell/BottomDock.jsx +450 -0
  140. package/src/shell/DetailsSlot.jsx +513 -0
  141. package/src/shell/LibrarySlot.jsx +86 -0
  142. package/src/shell/MenuBar.jsx +601 -0
  143. package/src/shell/OutlinerSlot.jsx +50 -0
  144. package/src/shell/PreferencesDialog.jsx +538 -0
  145. package/src/shell/PreferencesSlot.jsx +40 -0
  146. package/src/shell/StatusBar.jsx +125 -0
  147. package/src/shell/StudioShell.jsx +92 -0
  148. package/src/shell/TopBar.jsx +129 -0
  149. package/src/shell/ViewportToolbar.jsx +656 -0
  150. package/src/shell/agent-glass.css +296 -0
  151. package/src/shell/dock.css +93 -0
  152. package/src/shell/glass-regions.css +985 -0
  153. package/src/shell/glass.css +687 -0
  154. package/src/shell/log-store.js +52 -0
  155. package/src/shell/mode.css +9 -0
  156. package/src/shell/preferences.css +651 -0
  157. package/src/shell/shell.css +282 -0
  158. package/src/shell/studio-shell-context.js +19 -0
  159. package/src/shell/topbar.css +435 -0
  160. package/src/shell/viewport.css +451 -0
  161. package/src/store/authored-intent.js +22 -0
  162. package/src/store/runtime-adapters.js +92 -0
  163. package/src/store/scene-stage.js +21 -0
  164. package/src/store/use-document-store.js +14 -0
  165. package/src/studio-actions.js +210 -0
  166. package/src/studio-agent-commands.js +38 -268
  167. package/src/studio-agent-context.js +38 -9
  168. package/src/studio-agent-motion.js +122 -378
  169. package/src/studio-agent-protocol.js +66 -30
  170. package/src/studio-app-binding.js +379 -0
  171. package/src/studio-contact-sheet.js +73 -0
  172. package/src/studio-elements.js +58 -51
  173. package/src/styles/themes.css +200 -0
  174. package/src/styles/tokens.css +69 -0
  175. package/src/styles.css +443 -1753
  176. package/src/theme.js +44 -0
  177. package/src/timeline-extent.js +16 -0
  178. package/src/trail-key-conflicts.js +39 -0
  179. package/src/trail-pick.js +59 -0
  180. package/src/ui.jsx +8 -8
  181. package/src/use-case-question.jsx +66 -0
  182. package/src/workflow/AgentPanel.jsx +82 -69
  183. package/src/workflow/agent-client.js +12 -2
  184. package/src/workflow/agent-panel.css +34 -32
  185. package/src/workflow/cozy-scene-node.css +2 -0
  186. package/src/workflow/workflow.css +2 -0
  187. package/tools/ardy/__pycache__/cclay_gvhmr_worker.cpython-313.pyc +0 -0
  188. package/tools/ardy/bridge.mjs +164 -146
  189. package/tools/ardy/visual-qa.mjs +5 -5
  190. package/tools/bench/EXP3.md +61 -0
  191. package/tools/bench/cclay_bench_extract_incam.py +125 -0
  192. package/tools/bench/cclay_bench_extract_obs.py +204 -0
  193. package/tools/bench/cclay_bench_runner.py +42 -0
  194. package/tools/bench/cube-contact.mjs +162 -0
  195. package/tools/bench/exp3.mjs +152 -0
  196. package/tools/bench/extract-bench-lib.mjs +216 -0
  197. package/tools/bench/extract-bench.mjs +302 -0
  198. package/tools/bench/fal-generate.mjs +88 -0
  199. package/tools/bench/fit/README.md +189 -0
  200. package/tools/bench/fit/camera.mjs +59 -0
  201. package/tools/bench/fit/contact.mjs +419 -0
  202. package/tools/bench/fit/footlock.mjs +234 -0
  203. package/tools/bench/fit/motion.mjs +85 -0
  204. package/tools/bench/fit/pin.mjs +27 -0
  205. package/tools/bench/fit/remote.mjs +105 -0
  206. package/tools/bench/fit-bench.mjs +126 -0
  207. package/tools/bench/fit-sanity.mjs +45 -0
  208. package/tools/bench/metrics.mjs +313 -0
  209. package/tools/bench/obs/depth.mjs +258 -0
  210. package/tools/bench/obs/extrinsics.mjs +175 -0
  211. package/tools/bench/obs/fit_mannequin_betas.py +340 -0
  212. package/tools/bench/obs/ground.mjs +294 -0
  213. package/tools/bench/obs/heading.mjs +151 -0
  214. package/tools/bench/obs/ladder.mjs +555 -0
  215. package/tools/bench/obs/mannequin-betas.json +124 -0
  216. package/tools/bench/obs/remote.mjs +83 -0
  217. package/tools/bench/obs/rest_joints.py +52 -0
  218. package/tools/bench/obs/ybot-targets.mjs +49 -0
  219. package/tools/bench/obs-bench.mjs +520 -0
  220. package/tools/bench/score.mjs +343 -0
  221. package/tools/bench/summarize.mjs +86 -0
  222. package/tools/dev/pages/privacy.html +13 -8
  223. package/tools/gt-render/browser.mjs +159 -0
  224. package/tools/gt-render/camera-math.mjs +276 -0
  225. package/tools/gt-render/page.mjs +267 -0
  226. package/tools/gt-render/render.mjs +514 -0
  227. package/tools/gt-render/scene-box.mjs +31 -0
  228. package/tools/gt-render/take-transform.mjs +87 -0
  229. package/tools/qa/css-rule-usage.mjs +283 -0
  230. package/tools/qa/studio-control-count.mjs +70 -32
  231. package/tools/run-tests.mjs +58 -3
  232. package/tools/track/DESIGN.md +513 -0
  233. package/tools/track/backfill-provenance.mjs +116 -0
  234. package/tools/track/budget.mjs +8 -0
  235. package/tools/track/check-rig.mjs +209 -0
  236. package/tools/track/diagnostics.schema.json +60 -0
  237. package/tools/track/export-rig.mjs +256 -0
  238. package/tools/track/fallback.mjs +7 -0
  239. package/tools/track/fk-parity-fixture.mjs +161 -0
  240. package/tools/track/gate.mjs +349 -0
  241. package/tools/track/masks.mjs +318 -0
  242. package/tools/track/metrics.mjs +201 -0
  243. package/tools/track/publish-obs.mjs +108 -0
  244. package/tools/track/py/check_env.py +61 -0
  245. package/tools/track/py/eval_lr.py +229 -0
  246. package/tools/track/py/lr_viterbi.py +294 -0
  247. package/tools/track/py/masks.py +405 -0
  248. package/tools/track/py/objective.py +382 -0
  249. package/tools/track/py/rig.py +508 -0
  250. package/tools/track/py/scene.py +326 -0
  251. package/tools/track/py/test_joint_indices.py +123 -0
  252. package/tools/track/py/test_lr_viterbi.py +195 -0
  253. package/tools/track/py/test_masks.py +229 -0
  254. package/tools/track/py/test_rig.py +288 -0
  255. package/tools/track/py/test_scene.py +354 -0
  256. package/tools/track/py/test_track.py +328 -0
  257. package/tools/track/py/track.py +411 -0
  258. package/tools/track/remote.mjs +140 -0
  259. package/tools/track/rig-dump.mjs +227 -0
  260. package/tools/track/run-box-tests.mjs +14 -0
  261. package/tools/track/run-box.mjs +168 -0
  262. package/tools/track/setup-box.sh +59 -0
  263. package/tools/track/study-2d.mjs +728 -0
  264. package/dist/assets/analytics-B1hnH66c.js +0 -1
  265. package/dist/assets/app-Cu1cexZR.css +0 -1
  266. package/dist/assets/app-Dxdh8kds.js +0 -4861
  267. package/dist/assets/shot-prompt-C_g2BHVc.css +0 -1
  268. package/dist/assets/shot-prompt-HVJRP4Gr.js +0 -17
  269. package/dist/assets/workflow-CJd-PDtV.js +0 -179
  270. package/dist/assets/workflow-DsudxKHF.css +0 -1
  271. package/src/fal-motion-studio.jsx +0 -180
  272. package/src/scene-history.js +0 -129
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * fk-parity-fixture.mjs — Studio playback reference for the torch rig
4
+ * (tools/track/py/rig.py, test_rig.py tests (a) and (e); plan mocap-rearch todo 6).
5
+ *
6
+ * node tools/track/fk-parity-fixture.mjs [--model y-bot-tpose] [--out test/fixtures/track-fk-parity.json] [--seed 6]
7
+ *
8
+ * Loads the shipped FBX rig in node exactly like tools/track/export-rig.mjs,
9
+ * drives it with src/ardy/playback.js applyMotionFrame on seeded random cskel27
10
+ * poses, and records every control bone's world matrix (metres, 4x4 row-major,
11
+ * rig at the origin with its 0.01 root scale) plus 200 fixed skinned vertices
12
+ * (three's SkinnedMesh.getVertexPosition, indices into the export's merged
13
+ * vertex array). Each case is a 2-frame motion: frame 0 is the anchor frame,
14
+ * frame 1 is recorded, so anchoring is exercised. Cases 0-2 carry a per-joint
15
+ * boneScale (mocap take: grown offsets, stretched arm chain and hands); case 3
16
+ * has none (Studio's no-boneScale path, no stretch at all).
17
+ * posedJoints come from tools/bench/fit/motion.mjs regenerateJoints (JS FK), so
18
+ * the fixture also pins layer 1 (cskel27_fk) against the JS FK.
19
+ *
20
+ * Deterministic: a fixed-seed PRNG; numbers are float32 values printed with 9
21
+ * significant digits (exact float32 round trip).
22
+ */
23
+ import { writeFileSync } from "node:fs";
24
+ import { dirname, join, resolve } from "node:path";
25
+ import { fileURLToPath, pathToFileURL } from "node:url";
26
+ import * as THREE from "three";
27
+ import { applyMotionFrame } from "../../src/ardy/playback.js";
28
+ import { canonicalCskel27Reference } from "../../src/ardy/to-cskel27.js";
29
+ import { CSKEL27_JOINTS, CSKEL27_PARENTS } from "../../src/ardy/cskel27.js";
30
+ import { regenerateJoints } from "../bench/fit/motion.mjs";
31
+ import { loadRig, modelPath } from "./export-rig.mjs";
32
+
33
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
34
+ const J = 27;
35
+ const VERTEX_SAMPLES = 200;
36
+ const FIXTURE_VERSION = 1;
37
+
38
+ /** mulberry32: small, seedable, identical on every platform. */
39
+ export function prng(seed) {
40
+ let a = seed >>> 0;
41
+ return () => {
42
+ a = (a + 0x6d2b79f5) >>> 0;
43
+ let t = a;
44
+ t = Math.imul(t ^ (t >>> 15), t | 1);
45
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
46
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
47
+ };
48
+ }
49
+
50
+ /** Uniform random axis, angle in [0, maxAngle], as a row-major 3x3 (three.js math). */
51
+ function randomRotation(rand, maxAngle) {
52
+ const z = 2 * rand() - 1;
53
+ const phi = 2 * Math.PI * rand();
54
+ const r = Math.sqrt(1 - z * z);
55
+ const axis = new THREE.Vector3(r * Math.cos(phi), r * Math.sin(phi), z);
56
+ const m = new THREE.Matrix4().makeRotationAxis(axis, maxAngle * rand());
57
+ const e = m.elements; // column-major
58
+ return [e[0], e[4], e[8], e[1], e[5], e[9], e[2], e[6], e[10]];
59
+ }
60
+
61
+ function randomPose(rand, rotMats, rootPos, f) {
62
+ for (let j = 0; j < J; j += 1) {
63
+ // Root: any heading plus a moderate tilt; limbs up to 70 degrees.
64
+ let R = randomRotation(rand, j === 0 ? 0.35 : 1.2);
65
+ if (j === 0) {
66
+ const yaw = new THREE.Matrix4().makeRotationY(2 * Math.PI * rand() - Math.PI);
67
+ const tilt = new THREE.Matrix4().set(R[0], R[1], R[2], 0, R[3], R[4], R[5], 0, R[6], R[7], R[8], 0, 0, 0, 0, 1);
68
+ const e = yaw.multiply(tilt).elements;
69
+ R = [e[0], e[4], e[8], e[1], e[5], e[9], e[2], e[6], e[10]];
70
+ }
71
+ rotMats.set(R, (f * J + j) * 9);
72
+ }
73
+ rootPos.set([4 * rand() - 2, 0.8 + 0.3 * rand(), 4 * rand() - 2], f * 3);
74
+ }
75
+
76
+ const f9 = (x) => Number(Math.fround(x).toPrecision(9));
77
+ const list = (a) => Array.from(a, f9);
78
+ const rowMajor = (m) => list(m.clone().transpose().toArray());
79
+
80
+ export function buildFixture({ model = "y-bot-tpose", seed = 6 } = {}) {
81
+ const { rig, sha256 } = loadRig(modelPath(model));
82
+ // Control bones and merged vertex order exactly as export-rig.mjs dumpRig.
83
+ const control = [];
84
+ const seen = new Set();
85
+ rig.traverse((node) => { if (node.isBone && !seen.has(node.name)) { seen.add(node.name); control.push(node); } });
86
+ const meshes = [];
87
+ rig.traverse((node) => { if (node.isSkinnedMesh) meshes.push(node); });
88
+ const counts = meshes.map((m) => m.geometry.attributes.position.count);
89
+ const total = counts.reduce((a, b) => a + b, 0);
90
+
91
+ const rand = prng(seed);
92
+ const picked = new Set();
93
+ while (picked.size < VERTEX_SAMPLES) picked.add(Math.floor(rand() * total));
94
+ const vertexIndices = [...picked].sort((a, b) => a - b);
95
+ const locate = (v) => {
96
+ let m = 0;
97
+ while (v >= counts[m]) { v -= counts[m]; m += 1; }
98
+ return [meshes[m], v];
99
+ };
100
+
101
+ const cases = [];
102
+ for (let c = 0; c < 4; c += 1) {
103
+ const rotMats = new Float32Array(2 * J * 9);
104
+ const rootPos = new Float32Array(2 * 3);
105
+ for (let f = 0; f < 2; f += 1) randomPose(rand, rotMats, rootPos, f);
106
+ const withScale = c < 3;
107
+ const boneScale = Float32Array.from({ length: J }, (_, j) => (CSKEL27_PARENTS[j] === null ? 1 : 0.85 + 0.3 * rand()));
108
+ const motion = regenerateJoints({ frames: 2, fps: 30, rotMats, rootPos, posedJoints: new Float32Array(2 * J * 3), boneScale: withScale ? boneScale : undefined, anchorFrame: 0 });
109
+ if (!withScale) delete motion.boneScale;
110
+ applyMotionFrame(rig, motion, 1);
111
+ const p = new THREE.Vector3();
112
+ cases.push({
113
+ boneScale: withScale ? list(boneScale) : null,
114
+ anchorFrame: 0,
115
+ frame: 1,
116
+ rotMats: list(rotMats),
117
+ rootPos: list(rootPos),
118
+ posedJoints: list(motion.posedJoints),
119
+ boneWorld: control.flatMap((bone) => rowMajor(bone.matrixWorld)),
120
+ vertices: vertexIndices.flatMap((v) => {
121
+ const [mesh, local] = locate(v);
122
+ mesh.getVertexPosition(local, p).applyMatrix4(mesh.matrixWorld);
123
+ return [f9(p.x), f9(p.y), f9(p.z)];
124
+ }),
125
+ });
126
+ }
127
+ return {
128
+ version: FIXTURE_VERSION,
129
+ generator: "tools/track/fk-parity-fixture.mjs",
130
+ model,
131
+ fbxSha256: sha256,
132
+ seed,
133
+ units: "metres; matrices 4x4 row-major; rotMats row-major 3x3 per joint (npz local_rot_mats)",
134
+ joints: [...CSKEL27_JOINTS],
135
+ canonicalPosedJoints: canonicalCskel27Reference().posed_joints.map((row) => row.map(f9)),
136
+ bones: control.map((bone) => bone.name),
137
+ vertexIndices,
138
+ cases,
139
+ };
140
+ }
141
+
142
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
143
+ const args = { model: "y-bot-tpose", out: join(ROOT, "test/fixtures/track-fk-parity.json"), seed: 6 };
144
+ const argv = process.argv.slice(2);
145
+ for (let i = 0; i < argv.length; i += 2) {
146
+ const key = argv[i]?.replace(/^--/, "");
147
+ if (!(key in args) || argv[i + 1] === undefined) {
148
+ console.error("usage: fk-parity-fixture.mjs [--model <id>] [--out <path.json>] [--seed <int>]");
149
+ process.exit(2);
150
+ }
151
+ args[key] = key === "seed" ? Number(argv[i + 1]) : argv[i + 1];
152
+ }
153
+ try {
154
+ const fixture = buildFixture(args);
155
+ writeFileSync(resolve(args.out), `${JSON.stringify(fixture)}\n`);
156
+ console.log(JSON.stringify({ out: resolve(args.out), model: fixture.model, bones: fixture.bones.length, vertices: fixture.vertexIndices.length, cases: fixture.cases.length }));
157
+ } catch (error) {
158
+ console.error(`fk-parity-fixture: ${error.message}`);
159
+ process.exit(1);
160
+ }
161
+ }
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env node
2
+ /** Quality gates for one completed T1 run. */
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { readNpz } from "../kimodo/read-npz.mjs";
8
+ import { cameraFromJson } from "../bench/obs/extrinsics.mjs";
9
+ import { resolveObsOrigin } from "./masks.mjs";
10
+ import { hiddenJointError, occlusionAgreement, pelvisStepsDeg, resampleMotion, truthStanceSlideCmPerS } from "./metrics.mjs";
11
+ import { validateDiagnostics } from "./remote.mjs";
12
+ import { jointOccluded } from "./study-2d.mjs";
13
+
14
+ const USAGE = "usage: node tools/track/gate.mjs --run <dir> [--baseline <dir>] [--ceiling <summary.json>]\n Gbest comparisons use --run's own Gbest step. --baseline, if given, must be a run dir with item\n directories; no row reads values from it (historical run-492f comparisons live in study-2d / todo 14 tables).";
15
+ const TRUTH_SETS = new Set(["gt", "cube", "gt-skin", "cube-skin"]);
16
+ const HIDDEN_SETS = new Set(["cube", "cube-skin"]);
17
+ const HIDDEN_NAMES = new Set(["bump", "sit"]);
18
+ const SHADED_DETECTOR = ["p", "alette"].join("");
19
+ /** Score fields per scorer: tools/bench/score.mjs for truth sets, obs-bench scoreFal for fal. */
20
+ const TRUTH_SCORE_FIELDS = ["pose.paMpjpeM", "trajectory.rootErrorRawM.rmse", "trajectory.ateAlignedM.rmse", "overlap.maskIoURawMean"];
21
+ const FAL_SCORE_FIELDS = ["overlapIoU", "endpointFirstM", "endpointLastM", "maxPenetrationM"];
22
+ /** Obs manifest provenance the gate accepts: hashed at extraction, or hashed later from the path the sweep used. */
23
+ const ACCEPTED_PROVENANCE = ["recorded", "backfilled-path"];
24
+
25
+ function parseArgs(argv) {
26
+ const out = {};
27
+ for (let i = 0; i < argv.length; i += 1) {
28
+ const key = argv[i];
29
+ if (key === "--help" || key === "-h") { console.log(USAGE); process.exit(0); }
30
+ if (!["--run", "--baseline", "--ceiling"].includes(key)) throw new Error(`unknown option ${key}`);
31
+ const value = argv[++i];
32
+ if (!value || value.startsWith("--")) throw new Error(`${key} needs a value`);
33
+ out[key.slice(2)] = value;
34
+ }
35
+ if (!out.run) throw new Error("--run is required");
36
+ return { run: resolve(out.run), baseline: out.baseline ? resolve(out.baseline) : null, ceiling: out.ceiling ? resolve(out.ceiling) : null };
37
+ }
38
+ const readJson = path => JSON.parse(readFileSync(path, "utf8"));
39
+ const isFile = path => Boolean(path && existsSync(path) && statSync(path).isFile());
40
+ const finite = value => typeof value === "number" && Number.isFinite(value);
41
+ const field = (object, path) => path.split(".").reduce((value, key) => value?.[key], object);
42
+ const average = values => values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null;
43
+ const maximum = values => values.length ? Math.max(...values) : null;
44
+ const keyOf = item => `${item.set}/${item.name}`;
45
+
46
+ function itemDirs(root) {
47
+ if (!existsSync(root) || !statSync(root).isDirectory()) throw new Error(`no such run directory: ${root}`);
48
+ const out = [];
49
+ for (const set of readdirSync(root)) {
50
+ const setDir = join(root, set);
51
+ if (!statSync(setDir).isDirectory() || set.startsWith(".")) continue;
52
+ for (const name of readdirSync(setDir)) {
53
+ const dir = join(setDir, name);
54
+ if (statSync(dir).isDirectory()) out.push({ set, name, dir });
55
+ }
56
+ }
57
+ if (!out.length) throw new Error(`${root}: no item directories`);
58
+ return out;
59
+ }
60
+
61
+ /**
62
+ * { motion } or { motion: null, error }. Every measured series (pelvis angles,
63
+ * stance slide, joint errors) derives from posed_joints / local_rot_mats, so a
64
+ * non-finite value there makes the motion unmeasurable here, at the file
65
+ * boundary: downstream counts such as `angles.filter(v => v > 20)` would
66
+ * otherwise silently drop NaN and report a clean 0.
67
+ */
68
+ function readMotionChecked(path) {
69
+ if (!isFile(path)) return { motion: null, error: "missing" };
70
+ const members = readNpz(path);
71
+ const joints = members.posed_joints;
72
+ const rotations = members.local_rot_mats ?? members.rotMats;
73
+ if (!joints?.data || JSON.stringify(joints.shape?.slice(1)) !== "[27,3]") return { motion: null, error: "posed_joints is not [T,27,3]" };
74
+ const frames = joints.shape[0], fps = members.fps?.data?.[0] ?? 24;
75
+ if (!Number.isInteger(frames) || frames < 1 || !finite(fps) || fps <= 0) return { motion: null, error: "bad frame count or fps" };
76
+ if (!rotations?.data || rotations.data.length !== frames * 27 * 9) return { motion: null, error: "local_rot_mats is not [T,27,3,3]" };
77
+ for (const [name, data] of [["posed_joints", joints.data], ["local_rot_mats", rotations.data]]) {
78
+ const bad = data.findIndex(value => !Number.isFinite(value));
79
+ if (bad >= 0) return { motion: null, error: `non-finite ${name}[${bad}] = ${data[bad]}` };
80
+ }
81
+ return { motion: { frames, fps, posedJoints: joints.data, rotMats: rotations.data }, error: null };
82
+ }
83
+ function readMotion(path) { return readMotionChecked(path).motion; }
84
+ function nestedJoints(motion) {
85
+ return Array.from({ length: motion.frames }, (_, frame) => Array.from({ length: 27 }, (_, joint) => Array.from(motion.posedJoints.slice((frame * 27 + joint) * 3, (frame * 27 + joint + 1) * 3))));
86
+ }
87
+
88
+ function loadStep(item, step, { strict = true } = {}) {
89
+ const itemDir = item.itemDir ?? item.dir;
90
+ const dir = join(itemDir, step);
91
+ const resultPath = join(dir, "result.json"), scorePath = join(dir, "score", "score.json"), motionPath = join(dir, "motion.npz"), diagnosticsPath = join(dir, "diagnostics.json");
92
+ const errors = [];
93
+ const result = isFile(resultPath) ? readJson(resultPath) : null;
94
+ if (!result) errors.push(`${keyOf(item)}/${step}: missing result.json`);
95
+ if (strict) {
96
+ if (result?.step && result.step !== step) errors.push(`${keyOf(item)}/${step}: result.step is ${result.step}`);
97
+ if (result && result.ok !== true) errors.push(`${keyOf(item)}/${step}: result.ok is not true`);
98
+ if (result && result.fallback != null) errors.push(`${keyOf(item)}/${step}: fallback=${result.fallback}`);
99
+ if (result?.diagnostics?.failure) errors.push(`${keyOf(item)}/${step}: diagnostics.failure=${result.diagnostics.failure}`);
100
+ }
101
+ const score = isFile(scorePath) ? readJson(scorePath) : null;
102
+ const { motion, error: motionError } = readMotionChecked(motionPath);
103
+ const diagnostics = isFile(diagnosticsPath) ? readJson(diagnosticsPath) : null;
104
+ if (strict && !score) errors.push(`${keyOf(item)}/${step}: missing score.json`);
105
+ if (strict && score) {
106
+ const required = TRUTH_SETS.has(item.set) ? TRUTH_SCORE_FIELDS : FAL_SCORE_FIELDS;
107
+ for (const path of required) if (!finite(field(score, path))) errors.push(`${keyOf(item)}/${step}: missing score field ${path}`);
108
+ }
109
+ if (strict && !motion) errors.push(`${keyOf(item)}/${step}: motion.npz ${motionError}`);
110
+ if (strict && !diagnostics) errors.push(`${keyOf(item)}/${step}: missing diagnostics.json`);
111
+ if (strict && diagnostics) {
112
+ try { validateDiagnostics(diagnostics); }
113
+ catch (error) { errors.push(`${keyOf(item)}/${step}: ${error.message}`); }
114
+ if (diagnostics.failure) errors.push(`${keyOf(item)}/${step}: diagnostics.failure=${diagnostics.failure}`);
115
+ }
116
+ if (strict && TRUTH_SETS.has(item.set)) {
117
+ const source = field(result, "item.source") ?? field(result, "truthPath");
118
+ const truth = readMotionChecked(source);
119
+ if (!truth.motion) errors.push(`${keyOf(item)}/${step}: truth motion ${source ?? "?"} ${truth.error}`);
120
+ }
121
+ return { ...item, itemDir, step, dir, result, score, motion, motionError, motionPath, diagnostics, errors, valid: errors.length === 0 };
122
+ }
123
+ function loadT1(item) { return loadStep(item, "T1", { strict: true }); }
124
+ function loadG5(item) { return loadStep({ ...item, dir: item.itemDir ?? item.dir }, "G5", { strict: false }); }
125
+ function truthPath(record) { return field(record.result, "item.source") ?? field(record.result, "truthPath"); }
126
+ function truthMotion(record) { return readMotion(truthPath(record)); }
127
+ function scoreValue(record, path) { const value = field(record.score, path); return finite(value) ? value : null; }
128
+ function variantOf(record) { return record.result?.item?.variant ?? (record.set.endsWith("-skin") ? "skin" : "shaded"); }
129
+ function isHiddenItem(record) { return HIDDEN_SETS.has(record.set) && HIDDEN_NAMES.has(record.name); }
130
+
131
+ /**
132
+ * Truth visibility on the prediction's timeline: truth joints (spline-resampled
133
+ * to pred fps/frames) tested along the camera ray against the item's scene
134
+ * boxes, the same segment test the tracker's `occluded` flags use (true = visible).
135
+ */
136
+ function truthVisibility(record, truthOnPred) {
137
+ const cameraPath = field(record.result, "inputs.camera.path"), scenePath = field(record.result, "item.scene") ?? field(record.result, "inputs.scene");
138
+ if (!truthOnPred || !isFile(cameraPath) || !isFile(scenePath)) return null;
139
+ const centre = cameraFromJson(readJson(cameraPath)).t_c2w;
140
+ const scene = readJson(scenePath);
141
+ const boxes = Array.isArray(scene) ? scene : [scene];
142
+ const joints = truthOnPred.posedJoints.length / (truthOnPred.frames * 3);
143
+ return Array.from({ length: truthOnPred.frames }, (_, t) => Array.from({ length: joints }, (_, j) => {
144
+ const o = (t * joints + j) * 3;
145
+ return !jointOccluded(centre, [truthOnPred.posedJoints[o], truthOnPred.posedJoints[o + 1], truthOnPred.posedJoints[o + 2]], boxes);
146
+ }));
147
+ }
148
+ const sha256File = path => createHash("sha256").update(readFileSync(path)).digest("hex");
149
+ /**
150
+ * The obs the step consumed, traced to its original manifest (run copies are
151
+ * followed via `source`/`sourceSha256`, as masks.mjs does). Passes when that
152
+ * manifest's provenance is recorded|backfilled-path, its detector matches the
153
+ * appearance, the obs still has the recorded sha, and the item's extraction
154
+ * video (item.video for fal, else inputs.video) hashes to videoSha256.
155
+ */
156
+ function provenance(record) {
157
+ const fail = reason => ({ ok: false, kind: null, reason });
158
+ const obs = field(record.result, "inputs.obs");
159
+ let manifest = obs?.manifest ?? null, originObs = null;
160
+ if (isFile(obs?.obs)) {
161
+ try { ({ manifest, obs: originObs } = resolveObsOrigin(obs.obs)); }
162
+ catch (error) { return fail(error.message); }
163
+ } else if (manifest?.source) return fail(`obs copy ${obs?.obs ?? "?"} is missing`);
164
+ if (!manifest) return fail("no obs manifest");
165
+ const kind = manifest.provenance ?? "recorded";
166
+ if (!ACCEPTED_PROVENANCE.includes(kind)) return fail(`provenance ${kind} is not ${ACCEPTED_PROVENANCE.join("|")}`);
167
+ if (typeof manifest.videoSha256 !== "string" || !manifest.videoSha256) return fail("manifest has no videoSha256");
168
+ if (kind === "backfilled-path" && (typeof manifest.backfilledAt !== "string" || typeof manifest.obsSha256 !== "string")) return fail("backfilled manifest lacks backfilledAt/obsSha256");
169
+ if (typeof manifest.detector !== "string" || !manifest.detector) return fail("manifest has no detector");
170
+ const wanted = variantOf(record) === "skin" ? "yolo" : SHADED_DETECTOR;
171
+ if (manifest.detector !== wanted) return fail(`detector ${manifest.detector}, expected ${wanted}`);
172
+ if (originObs && manifest.obsSha256 && sha256File(originObs) !== manifest.obsSha256) return fail(`${originObs} changed after its manifest was written`);
173
+ const video = field(record.result, "item.video") ?? field(record.result, "inputs.video");
174
+ if (!isFile(video)) return fail(`video ${video ?? "?"} is missing`);
175
+ if (sha256File(video) !== manifest.videoSha256) return fail(`video ${video} does not hash to the manifest's videoSha256`);
176
+ return { ok: true, kind, reason: null };
177
+ }
178
+ function ceilingFor(ceiling, set) {
179
+ const perSet = ceiling?.iouCeiling?.perSet?.[set];
180
+ if (finite(perSet?.is1Threshold)) return perSet.is1Threshold;
181
+ if (finite(perSet?.meanIoURaw)) return perSet.meanIoURaw * 0.9;
182
+ return null;
183
+ }
184
+ function metric(record) {
185
+ const truth = truthMotion(record), motion = record.motion, diagnostics = record.diagnostics;
186
+ const out = {
187
+ record, truth, motion, diagnostics,
188
+ pa: scoreValue(record, "pose.paMpjpeM"), root: scoreValue(record, "trajectory.rootErrorRawM.rmse"), ate: scoreValue(record, "trajectory.ateAlignedM.rmse"),
189
+ iou: scoreValue(record, record.set === "fal" ? "overlapIoU" : "overlap.maskIoURawMean"),
190
+ endpointA: scoreValue(record, "endpointFirstM"), endpointB: scoreValue(record, "endpointLastM"),
191
+ scorerPenetrationCm: record.set === "fal" && finite(field(record.score, "maxPenetrationM")) ? record.score.maxPenetrationM * 100 : null,
192
+ stance: null, steps: null, agreement: null, hidden: null, g5Hidden: null, g5: null, hiddenError: null,
193
+ };
194
+ if (motion) out.steps = Array.from(pelvisStepsDeg(motion.rotMats, motion.frames)).filter(value => value > 20).length;
195
+ if (truth && motion) out.stance = truthStanceSlideCmPerS(motion, truth).meanCmPerS;
196
+ if (record.step === "T1") Object.assign(out, sameRunGbest(record, truth));
197
+ if (isHiddenItem(record) && diagnostics && motion && truth) {
198
+ try {
199
+ // Truth is compared on the prediction's timeline (e.g. 30 fps truth vs a 24 fps T1).
200
+ const truthOnPred = resampleMotion(truth, motion.fps, motion.frames);
201
+ const visibility = truthVisibility(record, truthOnPred);
202
+ if (!visibility) throw new Error("no truth visibility: item needs inputs.camera.path and item.scene");
203
+ out.agreement = occlusionAgreement(diagnostics.occluded, visibility).agreement;
204
+ const g5 = loadG5(record);
205
+ out.g5 = g5;
206
+ if (!g5.motion) throw new Error(`same-run G5 motion.npz ${g5.motionError}`);
207
+ out.hidden = hiddenJointError(nestedJoints(motion), nestedJoints(truthOnPred), diagnostics.occluded).meanM;
208
+ out.g5Hidden = hiddenJointError(nestedJoints(g5.motion), nestedJoints(truthOnPred), diagnostics.occluded).meanM;
209
+ } catch (error) { out.hiddenError = error.message; }
210
+ }
211
+ out.provenance = provenance(record);
212
+ return out;
213
+ }
214
+ /**
215
+ * Every "<= its Gbest" comparison in the IS table (IS-1 fal IoU and pelvis steps,
216
+ * IS-2 PA +5 mm, IS-4 stance slide re-measured with the same metric) uses the
217
+ * Gbest step of the SAME run dir, scored by the same scorer on the same obs;
218
+ * --baseline may not even hold this appearance set. Each value that cannot be
219
+ * read comes with a concrete `<name>Reason` instead.
220
+ */
221
+ function sameRunGbest(record, truth) {
222
+ const gbest = loadStep({ ...record, dir: record.itemDir ?? record.dir }, "Gbest", { strict: false });
223
+ const why = text => `${keyOf(record)}: ${text}`;
224
+ // Only a genuine Gbest result can be the comparator: a declared fallback or another step's
225
+ // result under Gbest/ (e.g. G5 standing in) would make a weaker baseline look like Gbest.
226
+ const declared = gbest.result, declaredItem = declared?.item;
227
+ const blocked = !declared ? why("no same-run Gbest/result.json")
228
+ : declared.ok !== true ? why("same-run Gbest result.ok is not true")
229
+ : declared.step !== "Gbest" ? why(`same-run Gbest/result.json declares step ${JSON.stringify(declared.step ?? null)}, not "Gbest"`)
230
+ : declared.fallback != null ? why(`same-run Gbest declares fallback=${declared.fallback}; not a Gbest comparator`)
231
+ : declaredItem && (declaredItem.set !== record.set || declaredItem.name !== record.name) ? why(`same-run Gbest/result.json is for ${declaredItem.set}/${declaredItem.name}`)
232
+ : null;
233
+ const out = {};
234
+ const put = (name, value, reason) => {
235
+ if (!blocked && finite(value)) { out[name] = value; out[`${name}Reason`] = null; }
236
+ else { out[name] = null; out[`${name}Reason`] = blocked ?? why(reason); }
237
+ };
238
+ put("gbestPa", scoreValue(gbest, "pose.paMpjpeM"), `same-run Gbest ${gbest.score ? "score.json has no pose.paMpjpeM" : "score/score.json missing"}`);
239
+ const iouField = record.set === "fal" ? "overlapIoU" : "overlap.maskIoURawMean";
240
+ put("gbestIou", scoreValue(gbest, iouField), `same-run Gbest ${gbest.score ? `score.json has no ${iouField}` : "score/score.json missing"}`);
241
+ const motionReason = `same-run Gbest motion.npz ${gbest.motionError}`;
242
+ put("gbestSteps", gbest.motion ? Array.from(pelvisStepsDeg(gbest.motion.rotMats, gbest.motion.frames)).filter(value => value > 20).length : null, motionReason);
243
+ const stance = gbest.motion && truth ? truthStanceSlideCmPerS(gbest.motion, truth).meanCmPerS : null;
244
+ put("gbestStance", stance, !gbest.motion ? motionReason : !truth ? "truth motion missing or invalid" : "same-run Gbest has no truth-stance samples");
245
+ return out;
246
+ }
247
+ /** Per-item "vs same-run Gbest" sub-check: missing Gbest values and violations are named, never compared as NaN. */
248
+ function gbestCheck(items, name, holds, describe) {
249
+ const missing = items.filter(m => !finite(m[name])).map(m => m[`${name}Reason`]);
250
+ const failing = items.filter(m => finite(m[name]) && !holds(m)).map(describe);
251
+ const problems = [...failing, ...missing];
252
+ return { pass: problems.length === 0, text: problems.length ? `[FAIL: ${problems.join("; ")}]` : "[ok]" };
253
+ }
254
+ function invalidDetails(metrics) { return metrics.flatMap(m => m.record.errors).join("; ") || "none"; }
255
+ function row(name, pass, detail) { return { name, pass: Boolean(pass), detail }; }
256
+ function allFinite(values) { return values.length > 0 && values.every(finite); }
257
+
258
+ function evaluate(runRecords, ceiling) {
259
+ const metrics = runRecords.map(metric);
260
+ const truth = metrics.filter(m => TRUTH_SETS.has(m.record.set));
261
+ const fal = metrics.filter(m => m.record.set === "fal");
262
+ const invalid = metrics.filter(m => !m.record.valid);
263
+ const rows = [];
264
+ const invalidText = invalidDetails(invalid);
265
+
266
+ const truthPa = truth.map(m => m.pa), truthRoot = truth.map(m => m.root), truthAte = truth.map(m => m.ate), truthIou = truth.map(m => m.iou);
267
+ const paGroups = [...new Set(truth.map(m => m.record.set))].map(set => ({ set, values: truth.filter(m => m.record.set === set).map(m => m.pa) }));
268
+ const paGbest = gbestCheck(truth, "gbestPa", m => finite(m.pa) && m.pa <= m.gbestPa + 0.005, m => `${keyOf(m.record)} ${finite(m.pa) ? m.pa * 1000 : "missing"} mm > Gbest ${m.gbestPa * 1000}+5 mm`);
269
+ const paMeanPass = paGroups.length > 0 && paGroups.every(group => allFinite(group.values) && average(group.values) <= 0.05);
270
+ const paPass = !invalid.length && paMeanPass && paGbest.pass;
271
+ rows.push(row("pose.paMpjpeM", paPass, invalidText !== "none" ? invalidText : `${paGroups.map(group => `${group.set} mean ${(average(group.values) ?? Infinity) * 1000} mm`).join(", ")} <= 50 mm per appearance set [${paMeanPass ? "ok" : "FAIL"}]; each <= same-run Gbest+5 mm ${paGbest.text}`));
272
+ rows.push(row("trajectory.rootErrorRawM", !invalid.length && allFinite(truthRoot) && average(truthRoot) <= 0.15, invalidText !== "none" ? invalidText : `${average(truthRoot) ?? "missing"} m <= 0.15 m`));
273
+ rows.push(row("trajectory.ateAlignedM", !invalid.length && allFinite(truthAte) && average(truthAte) <= 0.15, invalidText !== "none" ? invalidText : `${average(truthAte) ?? "missing"} m <= 0.15 m`));
274
+
275
+ const ceilingValues = truth.map(m => ceilingFor(ceiling, m.record.set));
276
+ const setIoU = [...new Set(truth.map(m => m.record.set))].map(set => {
277
+ const values = truth.filter(m => m.record.set === set).map(m => m.iou);
278
+ const threshold = ceilingFor(ceiling, set);
279
+ return { set, values, threshold, value: average(values) };
280
+ });
281
+ const iouPass = !invalid.length && setIoU.length > 0 && setIoU.every(group => allFinite(group.values) && finite(group.threshold) && group.value >= group.threshold);
282
+ rows.push(row("overlap.maskIoURawMean", iouPass, !ceiling ? "missing --ceiling truth IoU measurements" : setIoU.map(group => `${group.set}: ${group.value ?? "missing"} >= ${group.threshold ?? "missing"}`).join(", ")));
283
+
284
+ const falIou = fal.map(m => m.iou);
285
+ const falGbest = gbestCheck(fal, "gbestIou", m => finite(m.iou) && m.iou >= m.gbestIou - 0.02, m => `${keyOf(m.record)} IoU ${m.iou ?? "missing"} < Gbest ${m.gbestIou}-0.02`);
286
+ const falMeanPass = allFinite(falIou) && average(falIou) >= 0.4;
287
+ const falPass = !invalid.length && (!fal.length || (falMeanPass && falGbest.pass));
288
+ const falItems = fal.map(m => `${keyOf(m.record)} IoU ${m.iou ?? "missing"} (Gbest ${m.gbestIou ?? "missing"}) A ${m.endpointA ?? "missing"} m B ${m.endpointB ?? "missing"} m pen ${m.scorerPenetrationCm ?? "missing"} cm`).join("; ");
289
+ rows.push(row("fal.overlapIoU", falPass, !fal.length ? "no fal items" : `mean ${average(falIou) ?? "missing"} >= 0.4 [${falMeanPass ? "ok" : "FAIL"}]; every item >= same-run Gbest-0.02 ${falGbest.text} [${falItems}]`));
290
+
291
+ const stance = truth.map(m => m.stance), gbestStance = truth.map(m => m.gbestStance);
292
+ const stanceMissing = truth.filter(m => !finite(m.stance)).map(m => `${keyOf(m.record)}: T1 has no truth-stance samples`);
293
+ const gbestMissing = truth.filter(m => !finite(m.gbestStance)).map(m => m.gbestStanceReason);
294
+ const stanceMean = stanceMissing.length ? null : average(stance), gbestMean = gbestMissing.length ? null : average(gbestStance);
295
+ const capPass = finite(stanceMean) && stanceMean <= 2.5, gbestPass = finite(stanceMean) && finite(gbestMean) && stanceMean <= gbestMean;
296
+ const stanceText = `${stanceMean ?? `missing (${stanceMissing.join("; ") || "no truth items"})`} cm/s <= 2.5 [${capPass ? "ok" : "FAIL"}]; <= same-run Gbest mean ${gbestMean ?? `missing (${gbestMissing.join("; ") || "no truth items"})`} [${gbestPass ? "ok" : "FAIL"}]`;
297
+ rows.push(row("truthStanceSlideCmPerS", !invalid.length && capPass && gbestPass, invalidText !== "none" ? invalidText : stanceText));
298
+
299
+ // Fal items also carry the scorer's independent box penetration; the larger of the two counts.
300
+ const boxPen = metrics.map(m => { const own = m.diagnostics?.penetration?.maxBoxCm; return finite(own) && finite(m.scorerPenetrationCm) ? Math.max(own, m.scorerPenetrationCm) : own; }), floorPen = metrics.map(m => m.diagnostics?.penetration?.maxFloorCm);
301
+ rows.push(row("penetration.maxBoxCm", !invalid.length && allFinite(boxPen) && boxPen.every(value => value <= 1), invalidText !== "none" ? invalidText : `${maximum(boxPen) ?? "missing"} cm <= 1 cm`));
302
+ rows.push(row("penetration.maxFloorCm", !invalid.length && allFinite(floorPen) && floorPen.every(value => value <= 1), invalidText !== "none" ? invalidText : `${maximum(floorPen) ?? "missing"} cm <= 1 cm`));
303
+
304
+ const truthSteps = truth.map(m => m.steps);
305
+ const truthStepsPass = allFinite(truthSteps) && truthSteps.every(value => value === 0);
306
+ const falSteps = gbestCheck(fal, "gbestSteps", m => Number.isInteger(m.steps) && m.steps <= m.gbestSteps, m => `${keyOf(m.record)} ${m.steps ?? "missing"} frames > Gbest ${m.gbestSteps}`);
307
+ const pelvisPass = !invalid.length && truthStepsPass && falSteps.pass;
308
+ rows.push(row("pelvisSteps>20", pelvisPass, invalidText !== "none" ? invalidText : `${maximum(truthSteps) ?? "missing"} truth frames == 0 [${truthStepsPass ? "ok" : "FAIL"}]; Fal <= same-run Gbest ${fal.length ? falSteps.text : "[no fal items]"}`));
309
+
310
+ const hidden = metrics.filter(m => isHiddenItem(m.record));
311
+ const visibilityPass = !invalid.length && hidden.every(m => finite(m.agreement) && m.agreement >= 0.9);
312
+ rows.push(row("occlusionAgreement", visibilityPass, hidden.length ? hidden.map(m => `${keyOf(m.record)}: ${m.agreement ?? `missing (${m.hiddenError ?? "no T1 diagnostics/motion/truth"})`} >= 0.9`).join(", ") : "no cube occlusion items"));
313
+ const hiddenPass = !invalid.length && hidden.every(m => finite(m.hidden) && finite(m.g5Hidden) && m.hidden <= m.g5Hidden);
314
+ rows.push(row("hiddenJointErrorT1<=G5", hiddenPass, hidden.length ? hidden.map(m => `${keyOf(m.record)}: T1 ${m.hidden ?? "missing"} <= G5 ${m.g5Hidden ?? "missing"} on T1 flags`).join(", ") : "no cube occlusion items"));
315
+
316
+ // Input provenance is a property of the obs, independent of whether T1 itself fell back.
317
+ const provenancePass = metrics.length > 0 && metrics.every(m => m.provenance.ok);
318
+ const byKind = ACCEPTED_PROVENANCE.map(kind => [kind, metrics.filter(m => m.provenance.ok && m.provenance.kind === kind).map(m => keyOf(m.record))]).filter(([, items]) => items.length);
319
+ const provenanceText = [...byKind.map(([kind, items]) => `${kind} ${items.length} (${items.join(", ")})`), ...metrics.filter(m => !m.provenance.ok).map(m => `${keyOf(m.record)}: ${m.provenance.reason}`)].join("; ");
320
+ rows.push(row("obsProvenance", provenancePass, provenanceText || "no items"));
321
+ const runtimes = metrics.map(m => m.diagnostics?.runtime?.trackerSeconds), vram = metrics.map(m => m.diagnostics?.runtime?.peakReservedMiB);
322
+ const runtimePass = !invalid.length && allFinite(runtimes) && runtimes.every((value, index) => value <= ((metrics[index].motion?.frames ?? 0) <= 124 ? 180 : 540));
323
+ rows.push(row("runtime.trackerSeconds", runtimePass, invalidText !== "none" ? invalidText : `${maximum(runtimes) ?? "missing"} s`));
324
+ rows.push(row("runtime.peakReservedMiB", !invalid.length && allFinite(vram) && vram.every(value => value <= 5632), invalidText !== "none" ? invalidText : `${maximum(vram) ?? "missing"} MiB <= 5632 MiB`));
325
+ return { rows, metrics, invalid };
326
+ }
327
+
328
+ export function runGate(options) {
329
+ const runRecords = itemDirs(options.run).map(loadT1);
330
+ // --baseline stays accepted (the plan's gate command passes run-492f) but no IS row compares to
331
+ // it: every Gbest comparison uses the run's own Gbest step (sameRunGbest).
332
+ if (options.baseline) itemDirs(options.baseline);
333
+ const ceiling = options.ceiling ? readJson(options.ceiling) : null;
334
+ return evaluate(runRecords, ceiling);
335
+ }
336
+ export { evaluate };
337
+
338
+ async function main() {
339
+ let options;
340
+ try { options = parseArgs(process.argv.slice(2)); }
341
+ catch (error) { console.error(`${error.message}\n\n${USAGE}`); process.exitCode = 2; return; }
342
+ try {
343
+ const result = runGate(options);
344
+ let failed = 0;
345
+ for (const check of result.rows) { console.log(`${check.pass ? "PASS" : "FAIL"} ${check.name}: ${check.detail}`); if (!check.pass) failed += 1; }
346
+ if (failed) process.exitCode = 1;
347
+ } catch (error) { console.error(`gate error: ${error.message}`); process.exitCode = 2; }
348
+ }
349
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main();