@lunagerm-studio/video-cut-skill 0.0.0-stage → 1.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 (146) hide show
  1. package/README.md +13 -2
  2. package/package.json +12 -4
  3. package/skills/ai-video-opening/SKILL.md +62 -0
  4. package/skills/ai-video-opening/references/export-and-validation.md +9 -0
  5. package/skills/ai-video-opening/references/motion-and-layout.md +7 -0
  6. package/skills/ai-video-opening/references/series-cases.md +7 -0
  7. package/skills/blue-white-ui-motion/SKILL.md +30 -0
  8. package/skills/blue-white-ui-motion/agents/openai.yaml +2 -0
  9. package/skills/blue-white-ui-motion/references/review.md +25 -0
  10. package/skills/chengfeng-videocut-skills/LICENSE +201 -0
  11. package/skills/chengfeng-videocut-skills/NOTICE.md +27 -0
  12. package/skills/chengfeng-videocut-skills/README.md +265 -0
  13. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/SKILL.md +37 -0
  14. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/agents/openai.yaml +2 -0
  15. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/cut_video.sh +182 -0
  16. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/detect_en_stutter.js +49 -0
  17. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/generate_review.js +1484 -0
  18. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/generate_srt_for_video.sh +75 -0
  19. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/generate_subtitles.js +141 -0
  20. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/review_server.js +381 -0
  21. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/volcengine_transcribe.sh +224 -0
  22. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/watch_cut_done.js +86 -0
  23. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/1-/346/240/270/345/277/203/345/216/237/345/210/231.md +56 -0
  24. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/10-/345/210/240/351/231/244/351/243/216/351/231/251/345/210/206/345/261/202.md +44 -0
  25. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/11-/345/217/243/346/222/255/347/250/277/345/257/271/351/275/220.md +40 -0
  26. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/2-/350/257/255/346/260/224/350/257/215/346/243/200/346/265/213.md +30 -0
  27. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/3-/351/235/231/351/237/263/346/256/265/345/244/204/347/220/206.md +56 -0
  28. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/4-/351/207/215/345/244/215/346/243/200/346/265/213.md +77 -0
  29. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/5-/345/215/241/351/241/277/350/257/215.md +48 -0
  30. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/7-/350/277/236/347/273/255/350/257/255/346/260/224/350/257/215.md +32 -0
  31. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/9-/346/256/213/345/217/245/346/243/200/346/265/213.md +79 -0
  32. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/README.md +35 -0
  33. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/SKILL.md +32 -0
  34. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/agents/openai.yaml +2 -0
  35. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/references/artifact-contracts.md +168 -0
  36. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/animation_style.cjs +53 -0
  37. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/export_final_video.cjs +200 -0
  38. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/serve_range_preview.cjs +128 -0
  39. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/user_config.cjs +80 -0
  40. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/write_render_mode.cjs +149 -0
  41. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207//347/224/250/346/210/267/351/205/215/347/275/256/default.json +4 -0
  42. package/skills/chengfeng-videocut-skills//350/207/252/350/277/233/345/214/226/README.md +23 -0
  43. package/skills/chengfeng-videocut-skills//350/207/252/350/277/233/345/214/226/SKILL.md +126 -0
  44. package/skills/continuous-collage-motion/SKILL.md +30 -0
  45. package/skills/continuous-collage-motion/agents/openai.yaml +4 -0
  46. package/skills/continuous-collage-motion/references/reference-motion.md +32 -0
  47. package/skills/continuous-collage-motion/references/shot-plan.md +31 -0
  48. package/skills/continuous-collage-motion/references/style-check.md +17 -0
  49. package/skills/table-video/LICENSES/ATTRIBUTION.md +31 -0
  50. package/skills/table-video/LICENSES/CC-BY-4.0.txt +396 -0
  51. package/skills/table-video/LICENSES/MIT.txt +21 -0
  52. package/skills/table-video/SKILL.md +32 -0
  53. package/skills/table-video/SOURCES.md +61 -0
  54. package/skills/table-video/agents/openai.yaml +2 -0
  55. package/skills/table-video/references/complete-motion.md +97 -0
  56. package/skills/table-video/references/examples/01_/344/270/244/346/256/265/346/274/224/347/244/272.md +73 -0
  57. package/skills/table-video/references/examples/02_/347/224/237/345/233/276/347/224/237/350/247/206/351/242/221/346/217/220/347/244/272/350/257/215/347/244/272/344/276/213.md +50 -0
  58. package/skills/table-video/references/examples/03_DESIGN/345/241/253/345/206/231/347/244/272/344/276/213.md +333 -0
  59. package/skills/table-video/references/examples/04_/350/277/236/347/273/255MG/346/255/243/345/217/215/350/277/207/347/250/213.md +101 -0
  60. package/skills/table-video/references/examples/05_/345/256/214/346/225/264/350/277/207/347/250/213/346/272/220/347/240/201.md +55 -0
  61. package/skills/table-video/references/examples/05_/346/205/242/351/225/234/345/244/264/344/270/216/345/220/214/346/236/204/345/233/276/345/233/236/345/275/222.md +35 -0
  62. package/skills/table-video/references/experience//345/255/227/345/271/225/344/270/216/345/260/201/351/235/242.md +30 -0
  63. package/skills/table-video/references/experience//345/275/225/345/261/217/345/211/252/350/276/221.md +31 -0
  64. package/skills/table-video/references/experience//346/211/213/345/212/250/347/224/237/345/233/276/347/224/237/350/247/206/351/242/221.md +53 -0
  65. package/skills/table-video/references/experience//350/247/206/350/247/211/345/217/231/344/272/213/344/270/216/350/277/236/347/273/255MG.md +102 -0
  66. package/skills/table-video/references/experience//351/225/234/345/244/264/346/216/250/350/277/233/344/270/216/350/275/254/345/234/272.md +178 -0
  67. package/skills/table-video/references/intake.md +84 -0
  68. package/skills/table-video/references/library.md +26 -0
  69. package/skills/table-video/references/motion-check-method.md +147 -0
  70. package/skills/table-video/references/planning.md +62 -0
  71. package/skills/table-video/references/production.md +70 -0
  72. package/skills/table-video/references/project-rules.md +26 -0
  73. package/skills/table-video/references/review-and-repair.md +64 -0
  74. package/skills/table-video/references/self-diagnosis.md +46 -0
  75. package/skills/table-video/references/sop/01_/345/277/253/351/200/237/345/274/200/345/247/213.md +55 -0
  76. package/skills/table-video/references/sop/02_/345/210/266/344/275/234SOP.md +77 -0
  77. package/skills/table-video/references/sop/03_/347/233/256/345/275/225/344/270/216/345/271/266/350/241/214/345/215/217/344/275/234.md +72 -0
  78. package/skills/table-video/references/sop/04_/351/252/214/346/224/266/344/270/216/350/277/224/344/277/256.md +146 -0
  79. package/skills/table-video/references/sop/05_/346/226/207/346/241/210/346/243/200/346/237/245_/345/217/257/351/200/211.md +55 -0
  80. package/skills/table-video/references/sop/06_/351/237/263/346/225/210/344/270/216/351/205/215/344/271/220_/345/217/257/351/200/211.md +138 -0
  81. package/skills/table-video/references/sop/07_/345/267/245/345/205/267/344/270/216/347/216/257/345/242/203.md +52 -0
  82. package/skills/table-video/references/sop/08_/346/235/245/346/272/220/344/270/216/350/256/270/345/217/257.md +36 -0
  83. package/skills/table-video/references/sop/09_DESIGN/345/273/272/347/253/213/344/270/216/346/240/241/351/252/214.md +52 -0
  84. package/skills/table-video/references/state-contract.md +267 -0
  85. package/skills/table-video/references/style-and-motion.md +163 -0
  86. package/skills/table-video/schemas/request.schema.json +44 -0
  87. package/skills/table-video/schemas/state.schema.json +140 -0
  88. package/skills/table-video/scripts/cli.mjs +35 -0
  89. package/skills/table-video/scripts/core.mjs +977 -0
  90. package/skills/table-video/scripts/gain-proof.mjs +48 -0
  91. package/skills/table-video/scripts/init-project.mjs +7 -0
  92. package/skills/table-video/scripts/motion-audit.mjs +589 -0
  93. package/skills/table-video/scripts/motion-check.mjs +345 -0
  94. package/skills/table-video/scripts/motion-gates.mjs +997 -0
  95. package/skills/table-video/scripts/motion-observation.cjs +204 -0
  96. package/skills/table-video/scripts/preflight.mjs +24 -0
  97. package/skills/table-video/scripts/process-locate.mjs +57 -0
  98. package/skills/table-video/scripts/render-motion-example.mjs +143 -0
  99. package/skills/table-video/scripts/save-reference-image.mjs +249 -0
  100. package/skills/table-video/scripts/schema.mjs +71 -0
  101. package/skills/table-video/scripts/stillness.mjs +386 -0
  102. package/skills/table-video/scripts/storage.mjs +328 -0
  103. package/skills/table-video/scripts/workflow.mjs +24 -0
  104. package/skills/talking-head-motion-workflow/SKILL.md +36 -0
  105. package/skills/talking-head-motion-workflow/agents/openai.yaml +4 -0
  106. package/skills/talking-head-motion-workflow/references/cinematic-motion-and-sync.md +72 -0
  107. package/skills/talking-head-motion-workflow/references/classic-ui.md +11 -0
  108. package/skills/talking-head-motion-workflow/references/history-coverage.md +50 -0
  109. package/skills/talking-head-motion-workflow/references/layered-assets-and-characters.md +39 -0
  110. package/skills/talking-head-motion-workflow/references/layout-references.md +41 -0
  111. package/skills/talking-head-motion-workflow/references/lens-shot-selection.md +138 -0
  112. package/skills/talking-head-motion-workflow/references/live-interface-motion.md +69 -0
  113. package/skills/talking-head-motion-workflow/references/motion-recipes.md +40 -0
  114. package/skills/talking-head-motion-workflow/references/mouse-meter2-case.md +113 -0
  115. package/skills/talking-head-motion-workflow/references/pop-collage.md +61 -0
  116. package/skills/talking-head-motion-workflow/references/portable-production.md +32 -0
  117. package/skills/talking-head-motion-workflow/references/production-requirements.md +85 -0
  118. package/skills/talking-head-motion-workflow/references/reference-library.md +41 -0
  119. package/skills/talking-head-motion-workflow/references/safe-areas-and-sound.md +47 -0
  120. package/skills/talking-head-motion-workflow/references/scene-illustrations.md +19 -0
  121. package/skills/talking-head-motion-workflow/references/sfx-presets.md +57 -0
  122. package/skills/talking-head-motion-workflow/references/style-13-github-production.md +33 -0
  123. package/skills/talking-head-motion-workflow/references/style-13-scene-performance.md +76 -0
  124. package/skills/talking-head-motion-workflow/references/style-presets.md +111 -0
  125. package/skills/talking-head-motion-workflow/references/table-video-spatial-mg.md +36 -0
  126. package/skills/talking-head-motion-workflow/scripts/extract_docx.py +19 -0
  127. package/skills/talking-head-motion-workflow/scripts/generate_foley.py +93 -0
  128. package/skills/talking-head-motion-workflow/scripts/render_sfx.py +135 -0
  129. package/skills/video-production-review/SKILL.md +30 -0
  130. package/skills/video-production-review/agents/openai.yaml +2 -0
  131. package/skills/video-production-review/references/episode-review-desk.md +30 -0
  132. package/skills/video-production-review/references/motion-adjustment-review.md +21 -0
  133. package/skills/video-production-workflow/SKILL.md +76 -0
  134. package/skills/video-production-workflow/agents/openai.yaml +2 -0
  135. package/skills/video-production-workflow/references/table-video-ep09.md +17 -0
  136. package/skills/video-production-workflow/scripts/check_motion_project.py +83 -0
  137. package/skills/video-reference-analysis/SKILL.md +32 -0
  138. package/skills/video-reference-analysis/agents/openai.yaml +2 -0
  139. package/skills/video-reference-analysis/references/case-format.md +95 -0
  140. package/skills/video-reference-analysis/references/production-method.md +21 -0
  141. package/skills/video-reference-analysis/scripts/library.py +371 -0
  142. package/skills/video-resource-access/SKILL.md +35 -0
  143. package/skills/video-resource-access/online.enabled +1 -0
  144. package/skills/video-resource-access/scripts/asset_client.py +159 -0
  145. package/skills/video-resource-access/scripts/remote_library.py +50 -0
  146. package//345/256/211/350/243/205/350/257/264/346/230/216.txt +5 -0
@@ -0,0 +1,997 @@
1
+ #!/usr/bin/env node
2
+ // Gates 1/3 and an explicitly fixed camera are constraints; motion-style references are diagnostic.
3
+ // Gate 1 measures perceptual stillness, how long the composition stays unchanged and one-frame whole-scene changes
4
+ // on the decoded video (scripts/stillness.mjs), whatever the camera does: a declared fixed camera only proves the
5
+ // framing did not move, not that the picture keeps moving. Only source-backed role:'cut', scope:'scene' checkpoints
6
+ // (chapter boundaries or user-confirmed breaks) register a one-frame scene change.
7
+ // Camera arc uses the same screen projection as the ep05 census:
8
+ // [960+(x-cx)*z, 540+(y-cy)*z] on a 1920×1080 reference, independent of preview size.
9
+ // A constant vertical origin does not change arc length. frameAt().camera is the only pose source.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import {spawnSync} from 'node:child_process';
13
+ import {pathToFileURL, fileURLToPath} from 'node:url';
14
+ import {createRequire} from 'node:module';
15
+ import crypto from 'node:crypto';
16
+ import {auditMotion,cameraCutFrames} from './motion-audit.mjs';
17
+ import {measureStillness, scoreStillness} from './stillness.mjs';
18
+ import observation from './motion-observation.cjs';
19
+ const {visibleState,inspectActionCoverage}=observation;
20
+
21
+ export const DEFAULT_GATES = {
22
+ // Gate 1, perceptual stillness: 30fps, 480x270 gray, pixel delta >6/255, changed area <0.5% = nearly still.
23
+ // Calibrated 2026-11-08 on 8 approved Ep08 segments (18-43%, longest 1.1-1.8 s) and the rejected test (60%, 3.27 s).
24
+ stillPixelDelta: 6,
25
+ stillAreaPct: 0.5,
26
+ stillRatioMax: 0.5,
27
+ stillSegmentMax: 2,
28
+ stillReviewSec: 1.5,
29
+ // Gate 1, composition hold: 10fps, 32x18 gray; a run lasts while <3% of cells differ by >8/255 from its first frame.
30
+ // Calibrated 2026-11-08: 8 approved/accepted clips 0-11% of time in holds >2 s (longest 2.9 s);
31
+ // rejected 2026-11-07 clips 28-35%; stopped 2026-11-08 golden tests 81-100%.
32
+ compositionHoldSec: 2,
33
+ compositionShareMax: 0.2,
34
+ compositionSegmentMax: 4,
35
+ largeArcPx: 80,
36
+ minMeanPxPerSec: 358,
37
+ revealMaxSec: 1.5,
38
+ holdMaxSec: 4,
39
+ moveOnPxPerSec: 40,
40
+ followWindowSec: 0.5,
41
+ followMinFrames: 3,
42
+ followTargetMinFrames: 6,
43
+ followTargetMaxFrames: 9,
44
+ simultaneousFrames: 3,
45
+ clockFps: 60,
46
+ anticipationMinFrames: 6,
47
+ anticipationMaxFrames: 24,
48
+ anticipationDisplacementPx: 200,
49
+ anticipationAmpRefPx: 8,
50
+ anticipationNoisePx: 1,
51
+ contentWidthMin: 0.6,
52
+ refWidth: 1920,
53
+ refHeight: 1080,
54
+ };
55
+
56
+ export const EP05_REFERENCE = {
57
+ source: '第五期实测,2026-10-27 用户确认。全片静止来自总控 freezedetect 日志,不在本次重跑。',
58
+ freezeRatio: 0.14,
59
+ freezeMaxSec: 1.93,
60
+ freezeSegments: 60,
61
+ freezeSeconds: 63,
62
+ durationSec: 451.4,
63
+ bodyFreezeRatio: 0.15,
64
+ cameraDurationSec: 0.7,
65
+ cameraT80Sec: 0.43,
66
+ cameraMeanPxPerSec: 726,
67
+ cameraHoldSec: 1.15,
68
+ slowestSegmentMeanPxPerSec: 358,
69
+ anticipationAmpPx: 8,
70
+ deform: {compression: 0.07, stretch: 0.095, contact: 0.09, settle: 0.025},
71
+ };
72
+
73
+ const POS_EPS = 0.45;
74
+ const PROC_EPS = 0.008;
75
+ const SCALE_EPS = 0.008;
76
+
77
+ export function round(n, d = 1) {
78
+ if (n == null || !Number.isFinite(n)) return null;
79
+ const p = 10 ** d;
80
+ return Math.round(n * p) / p;
81
+ }
82
+ function quantile(sorted, q) {
83
+ if (!sorted.length) return null;
84
+ const i = (sorted.length - 1) * q;
85
+ const lo = Math.floor(i);
86
+ const hi = Math.ceil(i);
87
+ return lo === hi ? sorted[lo] : sorted[lo] * (hi - i) + sorted[hi] * (i - lo);
88
+ }
89
+ export function median(values) {
90
+ const s = values.filter(v => v != null && Number.isFinite(v)).sort((a, b) => a - b);
91
+ return quantile(s, 0.5);
92
+ }
93
+ function clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }
94
+ function framesOf(seconds, fps) { return seconds * fps; }
95
+ function nearly(a, b, eps = 1e-6) { return Math.abs(a - b) <= eps; }
96
+
97
+ export function parseClock(text) {
98
+ const m = /^(\d+):(\d+):(\d+(?:\.\d+)?)$/.exec(text);
99
+ if (!m) return null;
100
+ return Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]);
101
+ }
102
+
103
+ const stillGates = g => Object.fromEntries(Object.entries({
104
+ pixelDelta: g.stillPixelDelta, stillAreaPct: g.stillAreaPct, ratioMax: g.stillRatioMax, segmentMaxSec: g.stillSegmentMax, reviewSegmentSec: g.stillReviewSec,
105
+ compHoldSec: g.compositionHoldSec, compShareMax: g.compositionShareMax, compSegmentMaxSec: g.compositionSegmentMax,
106
+ }).filter(([, v]) => v !== undefined));
107
+
108
+ function overlaps(a0, a1, b0, b1) { return Math.min(a1, b1) - Math.max(a0, b0) > 1e-6; }
109
+
110
+ function estSpeed(a, b, dt) {
111
+ const z = Math.max(0.05, (a.z + b.z) / 2);
112
+ const pan = Math.hypot((b.cx - a.cx) * z, (b.cy - a.cy) * z) / dt;
113
+ const zoom = Math.abs(Math.log(b.z / a.z)) * 180 / dt;
114
+ return Math.max(pan, zoom);
115
+ }
116
+ function screenOf(cam, x, y) {
117
+ return [DEFAULT_GATES.refWidth / 2 + (x - cam.cx) * cam.z, DEFAULT_GATES.refHeight / 2 + (y - cam.cy) * cam.z];
118
+ }
119
+
120
+ export function measureMoves(samples, fps, gates = DEFAULT_GATES, camAt = null) {
121
+ if (samples.length < 3) return {error: '镜头采样少于 3 帧。', moves: []};
122
+ const dt = 1 / fps;
123
+ const poseAt = camAt || (t => {
124
+ let best = samples[0];
125
+ let bestD = Infinity;
126
+ for (const s of samples) {
127
+ const d = Math.abs(s.t - t);
128
+ if (d < bestD) { best = s; bestD = d; }
129
+ }
130
+ return best;
131
+ });
132
+ const on = samples.map((s, i) => i > 0 && estSpeed(samples[i - 1], s, dt) >= gates.moveOnPxPerSec);
133
+ const spans = [];
134
+ let i = 1;
135
+ while (i < samples.length) {
136
+ if (!on[i]) { i++; continue; }
137
+ let j = i;
138
+ while (j < samples.length && on[j]) j++;
139
+ let k = j;
140
+ while (k < samples.length && samples[k].t - samples[j - 1].t < 0.05) {
141
+ if (on[k]) j = k + 1;
142
+ k++;
143
+ }
144
+ const a = samples[i - 1];
145
+ const b = samples[j - 1];
146
+ if (b.t - a.t >= 2 / fps) spans.push([a.t, b.t]);
147
+ i = j;
148
+ }
149
+ // 弧长沿用普查:在同一次 frameAt().camera 上按约 4 倍帧率求值,不另造轨迹表。
150
+ const moves = spans.map(([a, b], idx) => {
151
+ const c0 = poseAt(a);
152
+ const center = {x: c0.cx, y: c0.cy};
153
+ const offset = {x: c0.cx + 180 / c0.z, y: c0.cy + 100 / c0.z};
154
+ const steps = Math.max(8, Math.round((b - a) * fps * 4));
155
+ const arcOf = world => {
156
+ let prev = screenOf(poseAt(a), world.x, world.y);
157
+ let arc = 0;
158
+ const cum = [0];
159
+ let peak = 0;
160
+ const times = [a];
161
+ for (let s = 1; s <= steps; s++) {
162
+ const t = a + (b - a) * s / steps;
163
+ const p = screenOf(poseAt(t), world.x, world.y);
164
+ const step = Math.hypot(p[0] - prev[0], p[1] - prev[1]);
165
+ const stepDt = (b - a) / steps;
166
+ peak = Math.max(peak, step / Math.max(1e-6, stepDt));
167
+ arc += step;
168
+ cum.push(arc);
169
+ times.push(t);
170
+ prev = p;
171
+ }
172
+ const total = cum[cum.length - 1] || 0;
173
+ let t50 = null;
174
+ let t80 = null;
175
+ for (let n = 1; n < cum.length; n++) {
176
+ if (t50 == null && cum[n] >= total * 0.5) t50 = times[n] - a;
177
+ if (t80 == null && cum[n] >= total * 0.8) t80 = times[n] - a;
178
+ }
179
+ return {arc: total, peak, t50, t80};
180
+ };
181
+ const C = arcOf(center);
182
+ const O = arcOf(offset);
183
+ const primary = O.arc > C.arc * 1.25 ? 'offset180' : 'center';
184
+ const P = primary === 'offset180' ? O : C;
185
+ const dur = b - a;
186
+ return {
187
+ i: idx, t0: a, t1: b, dur, primary,
188
+ arcPx: P.arc, mean: dur > 0 ? P.arc / dur : 0, peak: P.peak,
189
+ t50: P.t50, t80: P.t80, z0: c0.z,
190
+ };
191
+ });
192
+ return {moves};
193
+ }
194
+
195
+ function roleOf(move, roles) {
196
+ return (roles ?? []).find(r => move.t0 + move.dur / 2 >= r.t0 - 1e-6 && move.t0 + move.dur / 2 <= r.t1 + 1e-6) ?? null;
197
+ }
198
+
199
+ export function scoreCamera({moves, duration, gates = DEFAULT_GATES, roles = null, readings = [], windowStats = null}) {
200
+ if (!moves) return {status: '无法测量', reasons: ['没有镜头采样。'], measured: {}};
201
+ const large = moves.filter(m => m.arcPx + 1e-6 >= gates.largeArcPx);
202
+ if (!large.length) {
203
+ return {status: '无法测量', reasons: [`没有屏幕弧长 ≥ ${gates.largeArcPx}px 的镜头移动。`], measured: {moveCount: moves.length, largeCount: 0}};
204
+ }
205
+ const reasons = [];
206
+ const infoSlow = [];
207
+ const longReveal = [];
208
+ const holds = [];
209
+ const ordered = [...moves].sort((a, b) => a.t0 - b.t0 || a.t1 - b.t1);
210
+
211
+ // Historical window medians locate review candidates; they do not fail a shot.
212
+ if (windowStats) {
213
+ for (const w of windowStats) {
214
+ if (w.largeCount > 0 && w.medianMeanPxPerSec != null && w.medianMeanPxPerSec < gates.minMeanPxPerSec - 1e-6) {
215
+ reasons.push(`窗口 ${w.id}(${round(w.t0, 3)}–${round(w.t1, 3)})大移动 ${w.largeCount} 次,中位均速 ${w.medianMeanPxPerSec} px/s < ${gates.minMeanPxPerSec}。`);
216
+ }
217
+ }
218
+ } else {
219
+ // 无窗口信息时用全局中位数判
220
+ const globalMedian = median(large.map(m => m.mean));
221
+ if (globalMedian != null && globalMedian < gates.minMeanPxPerSec - 1e-6) {
222
+ reasons.push(`大移动 ${large.length} 次,中位均速 ${round(globalMedian, 0)} px/s < ${gates.minMeanPxPerSec}。`);
223
+ }
224
+ }
225
+
226
+ // 单次 < 358 逐次列出供审片参考,不判失败
227
+ for (const m of large) {
228
+ if (m.mean < gates.minMeanPxPerSec - 1e-6) {
229
+ infoSlow.push(m);
230
+ }
231
+ }
232
+
233
+ for (const m of large) {
234
+ if (m.dur > gates.revealMaxSec + 1e-9) {
235
+ const role = roleOf(m, roles);
236
+ const kind = role?.role ?? null;
237
+ if (!roles) {
238
+ reasons.push(`镜头 ${round(m.t0, 3)}–${round(m.t1, 3)} 长 ${round(m.dur, 3)} 秒,适配器没有标明是不是揭示或重构图。`);
239
+ longReveal.push({...m, kind: 'unclassified'});
240
+ } else if (!role) {
241
+ reasons.push(`镜头 ${round(m.t0, 3)}–${round(m.t1, 3)} 长 ${round(m.dur, 3)} 秒,没有落入已声明的镜头职责。`);
242
+ longReveal.push({...m, kind: 'unclassified'});
243
+ } else if ((kind === 'reveal' || kind === 'reframe') && !(role.slowReason && String(role.slowReason).trim())) {
244
+ reasons.push(`揭示或重构图 ${round(m.t0, 3)}–${round(m.t1, 3)} 长 ${round(m.dur, 3)} 秒,没有写明的情绪慢镜理由。`);
245
+ longReveal.push({...m, kind});
246
+ }
247
+ }
248
+ const next = ordered.find(x => x.t0 >= m.t1 - 1e-6 && (x.t0 !== m.t0 || x.t1 !== m.t1));
249
+ const gapEnd = next ? next.t0 : duration;
250
+ const gap = gapEnd == null ? null : gapEnd - m.t1;
251
+ if (gap != null && gap > gates.holdMaxSec + 1e-6) {
252
+ const reading = readings.find(r => r.valid !== false && overlaps(m.t1, Math.min(m.t1 + gates.holdMaxSec, gapEnd), r.t0, r.t1));
253
+ if (!reading) {
254
+ holds.push({t0: m.t1, gap});
255
+ reasons.push(`镜头在 ${round(m.t1, 3)} 结束,之后 ${round(gap, 3)} 秒内没有下一次移动,也没有标注写明的阅读对象。`);
256
+ }
257
+ }
258
+ }
259
+ const unclassified = reasons.some(r => r.includes('没有标明') || r.includes('没有落入'));
260
+ const measured = {
261
+ largeCount: large.length,
262
+ medianMeanPxPerSec: round(median(large.map(m => m.mean)), 0),
263
+ medianDurationSec: round(median(large.map(m => m.dur)), 3),
264
+ medianT50Sec: round(median(large.map(m => m.t50)), 3),
265
+ medianT80Sec: round(median(large.map(m => m.t80)), 3),
266
+ medianPeakPxPerSec: round(median(large.map(m => m.peak)), 1),
267
+ medianHoldSec: round(median(large.map(m => {
268
+ const next = ordered.find(x => x.t0 >= m.t1 - 1e-6 && (x.t0 !== m.t0 || x.t1 !== m.t1));
269
+ return next ? next.t0 - m.t1 : null;
270
+ })), 3),
271
+ slowestMeanPxPerSec: round(Math.min(...large.map(m => m.mean)), 1),
272
+ infoSlow: infoSlow.map(m => ({t0: round(m.t0, 3), t1: round(m.t1, 3), mean: round(m.mean, 1), arcPx: round(m.arcPx, 1)})),
273
+ holds: holds.map(h => ({t0: round(h.t0, 3), gap: round(h.gap, 3)})),
274
+ };
275
+ const missingRoles = large.filter(m => !roleOf(m, roles));
276
+ if (missingRoles.length && !unclassified) reasons.push('有镜头移动但缺少职责声明,须补本段观看依据。');
277
+ const status = unclassified || missingRoles.length ? '无法测量' : '诊断';
278
+ return {
279
+ status,
280
+ judgment: 'diagnostic',
281
+ visualAcceptance: 'not-assessed',
282
+ reasons,
283
+ measured,
284
+ reference: {
285
+ meanPxPerSec: EP05_REFERENCE.cameraMeanPxPerSec,
286
+ durationSec: EP05_REFERENCE.cameraDurationSec,
287
+ t80Sec: EP05_REFERENCE.cameraT80Sec,
288
+ holdSec: EP05_REFERENCE.cameraHoldSec,
289
+ floorPxPerSec: EP05_REFERENCE.slowestSegmentMeanPxPerSec,
290
+ },
291
+ };
292
+ }
293
+
294
+ function delta(a, b) {
295
+ const dx = (b.x ?? 0) - (a.x ?? 0);
296
+ const dy = (b.y ?? 0) - (a.y ?? 0);
297
+ const pos = Math.hypot(dx, dy) > POS_EPS;
298
+ const proc = ['maskProgress', 'pathProgress', 'morphProgress', 'occlusionProgress']
299
+ .some(k => Math.abs((b.process?.[k] ?? 0) - (a.process?.[k] ?? 0)) > PROC_EPS);
300
+ const scale = Math.abs((b.width ?? 0) - (a.width ?? 0)) > SCALE_EPS || Math.abs((b.height ?? 0) - (a.height ?? 0)) > SCALE_EPS;
301
+ const rot = Math.abs((b.rotation ?? 0) - (a.rotation ?? 0)) > 0.15;
302
+ const opacity = Math.abs((b.opacity ?? 1) - (a.opacity ?? 1)) > 0.01;
303
+ return {pos, proc, scale, rot, opacity, causal: pos || proc || scale || rot, dx, dy};
304
+ }
305
+
306
+ function objectAt(frame, id) {
307
+ return frame?.objects?.find(o => o.id === id) ?? null;
308
+ }
309
+
310
+ function visibleObject(o, viewport = {width: DEFAULT_GATES.refWidth, height: DEFAULT_GATES.refHeight}) {
311
+ return visibleState(o,viewport).state==='visible';
312
+ }
313
+ function localObject(o, frame, viewport = {width: DEFAULT_GATES.refWidth, height: DEFAULT_GATES.refHeight}) {
314
+ if (o.localGeometry) return {...o, ...o.localGeometry};
315
+ // A part without local geometry may still expose a real mask/path process;
316
+ // its inherited rectangle cannot establish its own movement.
317
+ if (o.parentId) return {...o, x: 0, y: 0, width: 0, height: 0, rotation: 0};
318
+ const c = frame?.camera;
319
+ if (c && !o.screenFixed) return {...o, x: (o.x - viewport.width / 2) / c.z + c.cx, y: (o.y - viewport.height / 2) / c.z + c.cy, width: o.width / c.z, height: o.height / c.z};
320
+ return o;
321
+ }
322
+
323
+ export function scoreFollow(samples, beat, gates = DEFAULT_GATES) {
324
+ const scope = {visualAcceptance: 'not-assessed', relationship: beat.timelineRelay ? 'timeline-declared-not-verified' : 'not-assessed', basis: 'Visible declared-object onset timing only; neither causal connection nor expressive strength is established'};
325
+ if (beat.subjectId === beat.attachmentId) return {id: beat.id, ...scope, status: '无法测量', reasons: ['主体与跟随件是同一个对象,不能测部件接力。']};
326
+ const fps = gates.clockFps;
327
+ if (samples.length < 3) return {id: beat.id, status: '无法测量', reasons: ['跟随窗口采样不足。']};
328
+ let subjectOn = null;
329
+ let attachOn = null;
330
+ let receiveOn = null;
331
+ const declaredTrigger = beat.trigger?.time ?? beat.triggerTime;
332
+ if (declaredTrigger != null && (!Number.isFinite(declaredTrigger) || declaredTrigger < samples[0].t - 1e-9 || declaredTrigger > samples.at(-1).t + 1e-9))
333
+ return {id:beat.id,...scope,status:'无法测量',reasons:['实际触发时间无效或不在采样范围内。']};
334
+ const unresolved = samples.some(s => [beat.subjectId,beat.attachmentId].some(id => {
335
+ const object=objectAt(s.frame,id);
336
+ return !object || visibleState(object,beat.viewport).state==='unknown';
337
+ }));
338
+ if(unresolved)return {id:beat.id,...scope,status:'无法测量',reasons:['主体或部件的实际绘制可见性缺测;须从同源变换、路径和触发数据补测并核像素。']};
339
+ const withinAction = (range, i) => !range || (samples[i - 1].t >= range[0] - 1e-9 && samples[i].t <= range[1] + 1e-9);
340
+ for (let i = 1; i < samples.length; i++) {
341
+ const s0 = objectAt(samples[i - 1].frame, beat.subjectId);
342
+ const s1 = objectAt(samples[i].frame, beat.subjectId);
343
+ const a0 = objectAt(samples[i - 1].frame, beat.attachmentId);
344
+ const a1 = objectAt(samples[i].frame, beat.attachmentId);
345
+ if (!s0 || !s1 || !a0 || !a1) continue;
346
+ const sd = delta(localObject(s0, samples[i - 1].frame, beat.viewport), localObject(s1, samples[i].frame, beat.viewport));
347
+ const ad = delta(localObject(a0, samples[i - 1].frame, beat.viewport), localObject(a1, samples[i].frame, beat.viewport));
348
+ const subjectVisible = visibleObject(s0, beat.viewport) && visibleObject(s1, beat.viewport);
349
+ const attachmentVisible = visibleObject(a0, beat.viewport) && visibleObject(a1, beat.viewport);
350
+ const subjectAction = withinAction(beat.timelineRelay?.fromRange, i);
351
+ const attachmentAction = withinAction(beat.timelineRelay?.toRange, i);
352
+ if (subjectOn == null && subjectVisible && subjectAction && (sd.pos || sd.proc)) subjectOn = samples[i].t;
353
+ if (attachOn == null && attachmentVisible && attachmentAction && ad.causal) attachOn = samples[i].t;
354
+ if (attachOn != null && receiveOn == null && attachmentVisible && attachmentAction && samples[i].t > attachOn + (gates.simultaneousFrames / fps) && (ad.proc || ad.scale || ad.rot)) receiveOn = samples[i].t;
355
+ }
356
+ if (subjectOn == null) return {id: beat.id, ...scope, status: '无法测量', reasons: [`${beat.subjectId} 在窗口内没有可见的位置或揭示变化。`]};
357
+ const triggerTime = declaredTrigger ?? subjectOn;
358
+ const triggerKind = beat.trigger?.kind ?? (declaredTrigger == null ? 'measured-subject-onset' : 'declared-production-event');
359
+ const measured = {triggerTime:round(triggerTime,6),triggerKind,subjectOn:round(subjectOn,3),attachmentOn:round(attachOn,3),rigid:!!beat.rigid};
360
+ const reasons = [];
361
+ if (attachOn == null || attachOn - triggerTime > gates.followWindowSec + 1e-6) {
362
+ reasons.push(`${beat.attachmentId} 没有在实际触发事件后 ${gates.followWindowSec} 秒内发生位置、遮罩或形变。`);
363
+ return {id: beat.id, ...scope, status: '未通过', reasons, measured};
364
+ }
365
+ const delay = attachOn - triggerTime;
366
+ const delayFrames = framesOf(delay, fps);
367
+ Object.assign(measured,{delaySec:round(delay,4),delayFrames:round(delayFrames,2),subjectDelaySec:round(attachOn-subjectOn,4)});
368
+ if(delay < -1e-6)reasons.push('附属件在实际触发事件之前响应,因果顺序不成立。');
369
+ if (beat.rigid) {
370
+ // 测到的是后续遮罩/形变/旋转,是否真是接收反馈仍须看实际画面。
371
+ if (receiveOn == null || receiveOn < triggerTime || receiveOn-triggerTime > gates.followWindowSec + 1e-6) reasons.push('刚性组缺少实际触发窗口内的接收反馈(遮罩、形变或旋转)。');
372
+ else measured.receiveOn = round(receiveOn, 3);
373
+ } else if (delayFrames < gates.simultaneousFrames - 1e-6) {
374
+ reasons.push(`错开 ${round(delayFrames, 2)} 帧 < ${gates.simultaneousFrames} 帧,视为同时。`);
375
+ }
376
+ // 6–9 帧是目标参照,不作为失败线
377
+ if (!beat.rigid && delayFrames >= gates.simultaneousFrames - 1e-6) {
378
+ measured.targetNote = delayFrames >= gates.followTargetMinFrames - 1e-6 && delayFrames <= gates.followTargetMaxFrames + 1e-6
379
+ ? '在目标参照 6–9 帧内' : '不在目标参照 6–9 帧内(不判失败)';
380
+ }
381
+ return {id: beat.id, ...scope, status: reasons.length ? '未通过' : '通过', reasons, measured};
382
+ }
383
+
384
+ function pathLength(samples, id, t0, t1) {
385
+ let arc = 0;
386
+ let prev = null;
387
+ for (const s of samples) {
388
+ if (s.t < t0 - 1e-9 || s.t > t1 + 1e-9) continue;
389
+ const o = objectAt(s.frame, id);
390
+ if (!o) continue;
391
+ if (prev) arc += Math.hypot(o.x - prev.x, o.y - prev.y);
392
+ prev = o;
393
+ }
394
+ return arc;
395
+ }
396
+
397
+ export function scoreAnticipation(samples, beat, gates = DEFAULT_GATES) {
398
+ const fps = gates.clockFps;
399
+ const minSec = gates.anticipationMinFrames / fps;
400
+ const maxSec = gates.anticipationMaxFrames / fps;
401
+ const inWindow = samples.filter(s => s.t >= beat.t0 - maxSec - 1e-9 && s.t <= beat.t1 + 1e-9);
402
+ if (inWindow.length < 4) return {id: beat.id, status: '无法测量', reasons: ['预备窗口采样不足。']};
403
+ if(inWindow.some(s=>!objectAt(s.frame,beat.subjectId)||visibleState(objectAt(s.frame,beat.subjectId),beat.viewport).state==='unknown'))
404
+ return {id:beat.id,status:'无法测量',reasons:['预备窗口包含缺失或未决绘制,诊断不能视为通过。']};
405
+ const steps = [];
406
+ let visiblePairs = 0;
407
+ for (let i = 1; i < inWindow.length; i++) {
408
+ const sa = objectAt(inWindow[i - 1].frame, beat.subjectId);
409
+ const sb = objectAt(inWindow[i].frame, beat.subjectId);
410
+ if (!visibleObject(sa, beat.viewport) || !visibleObject(sb, beat.viewport)) continue;
411
+ visiblePairs++;
412
+ const a = localObject(sa, inWindow[i - 1].frame, beat.viewport), b = localObject(sb, inWindow[i].frame, beat.viewport);
413
+ const dx = b.x - a.x;
414
+ const dy = b.y - a.y;
415
+ const len = Math.hypot(dx, dy);
416
+ const squash = (a.width - b.width) / (a.width || 1);
417
+ if (len <= 0.05 && !(squash > 0.02)) continue;
418
+ steps.push({t0: inWindow[i - 1].t, t1: inWindow[i].t, dx, dy, len, squash, a, b});
419
+ }
420
+ const runs = [];
421
+ if (!visiblePairs) return {id: beat.id, status: '无法测量', reasons: ['预备窗口内没有连续可见的主体采样。'], visualAcceptance: 'not-assessed'};
422
+ for (const step of steps) {
423
+ const prev = runs[runs.length - 1];
424
+ const aligned = prev && step.t0 - prev.t1 <= 1.5 / fps && (prev.dx * step.dx + prev.dy * step.dy) >= -1e-6;
425
+ if (!prev || !aligned) runs.push({t0: step.t0, t1: step.t1, dx: step.dx, dy: step.dy, path: step.len, squash: step.squash});
426
+ else {
427
+ prev.t1 = step.t1;
428
+ prev.dx += step.dx;
429
+ prev.dy += step.dy;
430
+ prev.path += step.len;
431
+ prev.squash = Math.max(prev.squash, step.squash);
432
+ }
433
+ }
434
+ const main = beat.reveal === true
435
+ ? (runs.find(r => r.path + 1e-6 >= gates.anticipationDisplacementPx) ?? runs[runs.length - 1] ?? null)
436
+ : runs.find(r => r.path + 1e-6 >= gates.anticipationDisplacementPx) ?? null;
437
+ if (!main) {
438
+ return {id: beat.id, status: beat.reveal ? '无法测量' : '诊断', judgment:'diagnostic', reasons: beat.reveal ? ['声明了揭示,但没有采到主体位移。'] : [], measured: {triggered: false, travelPx: round(Math.max(0, ...runs.map(r => r.path), 0), 1), note: '未达到历史位移取样参照;重量仍按实际过程判断。'}};
439
+ }
440
+ const travel = main.path;
441
+ const reasons = [];
442
+ const prev = runs[runs.indexOf(main) - 1];
443
+ const dir = Math.hypot(main.dx, main.dy) || 1;
444
+ let amp = 0;
445
+ let prepDur = null;
446
+ if (prev && main.t0 - prev.t1 <= 1.5 / fps) {
447
+ const along = (prev.dx * main.dx + prev.dy * main.dy) / dir;
448
+ const reverse = along < -gates.anticipationNoisePx;
449
+ const squash = !beat.rigid && prev.squash > 0.02;
450
+ prepDur = main.t0 - prev.t0;
451
+ amp = reverse ? -along : 0;
452
+ if (!(reverse || squash) || prepDur + 1e-9 < minSec || prepDur > maxSec + 1e-9) {
453
+ reasons.push(`主动作前的预备持续 ${round(prepDur, 3)} 秒,不在 ${round(minSec, 3)}–${round(maxSec, 3)} 秒的反向预备或蓄力里。`);
454
+ }
455
+ } else {
456
+ reasons.push(`主动作前 ${gates.anticipationMinFrames}–${gates.anticipationMaxFrames} 帧没有反向预备或蓄力。`);
457
+ }
458
+ const measured = {triggered: true, travelPx: round(travel, 1), mainStart: round(main.t0, 3), anticipationSec: prepDur == null ? null : round(prepDur, 3), anticipationAmpPx: round(amp, 1), ampRefPx: gates.anticipationAmpRefPx, rigid: !!beat.rigid};
459
+ return {id: beat.id, status: '诊断', judgment:'diagnostic', visualAcceptance:'not-assessed', reasons, measured};
460
+ }
461
+
462
+ function visibleContent(o, gates) {
463
+ return visibleState(o,{width:gates.refWidth,height:gates.refHeight}).state==='visible';
464
+ }
465
+
466
+ function unionWidth(frame, ids, gates) {
467
+ let x0 = Infinity;
468
+ let x1 = -Infinity;
469
+ for (const id of ids) {
470
+ const o = objectAt(frame, id);
471
+ if (!visibleContent(o, gates)) continue;
472
+ const measured=o.observation?.visibleBounds??o;
473
+ x0 = Math.min(x0, measured.x);
474
+ x1 = Math.max(x1, measured.x + measured.width);
475
+ }
476
+ if (!Number.isFinite(x0)) return null;
477
+ return clamp(x1, 0, gates.refWidth) - clamp(x0, 0, gates.refWidth);
478
+ }
479
+
480
+ export function scoreComposition(samples, cast, gates = DEFAULT_GATES) {
481
+ const ids = cast?.mainContentIds;
482
+ if (!ids?.length) return {status: '无法测量', reasons: ['没有声明主要内容对象,不能算外接框。'], measured: {}};
483
+ const unresolved=ids.filter(id=>samples.some(s=>visibleState(objectAt(s.frame,id),{width:gates.refWidth,height:gates.refHeight}).state==='unknown'));
484
+ const cameraSamples = samples.filter(s => s.camera);
485
+ const moving = new Set();
486
+ for (let i = 1; i < cameraSamples.length; i++) {
487
+ const dt = cameraSamples[i].t - cameraSamples[i - 1].t || 1 / 60;
488
+ if (estSpeed(cameraSamples[i - 1].camera, cameraSamples[i].camera, dt) >= gates.moveOnPxPerSec) moving.add(cameraSamples[i].t);
489
+ }
490
+ // Stable display requires a neighboring unchanged content state as well as a quiet camera.
491
+ // Keep animated reveals out of this display-width check, but do not average a narrow hold away.
492
+ const sameContent = (a, b) => ids.every(id => {
493
+ const x = objectAt(a.frame, id), y = objectAt(b.frame, id);
494
+ const shownX = visibleContent(x, gates), shownY = visibleContent(y, gates);
495
+ if (!shownX && !shownY) return true;
496
+ if (shownX !== shownY) return false;
497
+ const d = delta(x, y);
498
+ return !d.causal && !d.opacity;
499
+ });
500
+ const stable = samples.filter((s, i) => !moving.has(s.t) &&
501
+ ((i > 0 && !moving.has(samples[i - 1].t) && sameContent(samples[i - 1], s)) ||
502
+ (i + 1 < samples.length && !moving.has(samples[i + 1].t) && sameContent(s, samples[i + 1]))));
503
+ const ratios = [];
504
+ const narrowIntervals = [];
505
+ const sampleIndices = new Map(samples.map((s, i) => [s, i]));
506
+ let previousStableIndex = null;
507
+ let lastNarrow = false;
508
+ for (const s of stable) {
509
+ const sampleIndex = sampleIndices.get(s);
510
+ if (previousStableIndex !== sampleIndex - 1) lastNarrow = false;
511
+ previousStableIndex = sampleIndex;
512
+ if ((cast.emptyMood ?? []).some(ex => ex.valid !== false && s.t >= ex.t0 && s.t <= ex.t1)) {lastNarrow = false; continue;}
513
+ const w = unionWidth(s.frame, ids, gates);
514
+ if (w == null) {lastNarrow = false; continue;}
515
+ const ratio = w / gates.refWidth;
516
+ ratios.push(ratio);
517
+ if (ratio < gates.contentWidthMin - 1e-9) {
518
+ if (lastNarrow) {const interval = narrowIntervals.at(-1); interval.end = s.t; interval.samples++; interval.minWidthRatio = Math.min(interval.minWidthRatio, ratio);}
519
+ else narrowIntervals.push({start: s.t, end: s.t, samples: 1, minWidthRatio: ratio});
520
+ lastNarrow = true;
521
+ } else lastNarrow = false;
522
+ }
523
+ if (!ratios.length) return {status: '无法测量', reasons: ['没有可测量的稳定展示帧。',...(unresolved.length?['绘制可见性未决:'+unresolved.join(', ')]:[])], measured: {unresolvedVisibilityObjectIds:unresolved}};
524
+ const med = median(ratios);
525
+ const worst = Math.min(...ratios);
526
+ const reasons = [];
527
+ for (const interval of narrowIntervals) reasons.push(`稳定展示 ${round(interval.start, 3)}–${round(interval.end, 3)} 的主要内容外接框宽度最低 ${(interval.minWidthRatio * 100).toFixed(1)}% < ${(gates.contentWidthMin * 100).toFixed(0)}%,不能由全段中位数抵消。`);
528
+ return {
529
+ status: unresolved.length ? '无法测量' : '诊断',
530
+ judgment: 'diagnostic',
531
+ visualAcceptance: 'not-assessed',
532
+ reasons: [...reasons,...(unresolved.length?['绘制可见性未决:'+unresolved.join(', ')]:[])],
533
+ measured: {stableFrames: ratios.length, medianWidthRatio: round(med, 3), minWidthRatio: round(worst, 3), narrowIntervals, unresolvedVisibilityObjectIds:unresolved,basis: 'Stable confirmed-painted content width only; spacing, legibility and semantic composition not assessed'},
534
+ reference: {minWidthRatio: gates.contentWidthMin},
535
+ };
536
+ }
537
+
538
+ function anchorOk(item, baseDir) {
539
+ if (!item?.sourceFile || !item?.anchor) return {valid: false, reason: '例外或承诺没有源文件锚点。'};
540
+ const file = path.resolve(baseDir, item.sourceFile);
541
+ if (!fs.existsSync(file)) return {valid: false, reason: `找不到锚点文件 ${file}。`};
542
+ const text = fs.readFileSync(file, 'utf8');
543
+ if (!text.includes(item.anchor)) return {valid: false, reason: `锚点不在源文件中:${item.anchor}`};
544
+ return {valid: true};
545
+ }
546
+
547
+ function bindList(list, baseDir) {
548
+ return (list ?? []).map(item => {
549
+ const check = anchorOk(item, baseDir);
550
+ return {...item, valid: check.valid, anchorReason: check.reason ?? null};
551
+ });
552
+ }
553
+
554
+ export function sampleFrames(frameAt, t0, t1, fps) {
555
+ const samples = [];
556
+ const dt = 1 / fps;
557
+ for (let t = t0; t <= t1 + 1e-9; t += dt) {
558
+ const time = Math.min(t, t1);
559
+ const frame = frameAt(time);
560
+ if (!frame || !Array.isArray(frame.objects)) throw new Error(`frameAt(${time}) 没有 objects。`);
561
+ const camera = frame.camera ?? null;
562
+ if (camera && (![camera.cx, camera.cy, camera.z].every(Number.isFinite) || camera.z <= 0)) throw new Error(`frameAt(${time}) 的 camera 无效。`);
563
+ samples.push({t: time, frame, camera});
564
+ }
565
+ return samples;
566
+ }
567
+
568
+ function mergeGate(parts) {
569
+ if (!parts.length) return {status: '无法测量', reasons: ['没有可计算的条目。'], measured: {items: []}};
570
+ if (parts.some(p => p.status === '未通过')) return {status: '未通过', reasons: parts.flatMap(p => p.reasons ?? []), measured: {items: parts}};
571
+ if (parts.some(p => p.status === '无法测量')) return {status: '无法测量', reasons: parts.flatMap(p => p.reasons ?? []), measured: {items: parts}};
572
+ if (parts.some(p => p.status === '诊断')) return {status:'诊断',judgment:'diagnostic',reasons:parts.flatMap(p=>p.reasons??[]),measured:{items:parts}};
573
+ return {status: '通过', reasons: [], measured: {items: parts}};
574
+ }
575
+
576
+ // Reuse the production timeline and coverage. Legacy motionCast remains a limited
577
+ // numeric input, never evidence that all promised component actions were covered.
578
+ export function deriveMotionCast(spec) {
579
+ const cast = {...(spec.motionCast ?? {})};
580
+ const actions = spec.actions ?? [], relays = spec.relays ?? [];
581
+ const follows = relays.filter(r => ['follow', 'rigid-feedback'].includes(r.motionGate)).map(r => {
582
+ const from = actions.find(a => a.id === r.fromAction), to = actions.find(a => a.id === r.toAction);
583
+ const valid = !!from && !!to && from.objectId !== to.objectId && (spec.coverage?.objectIds ?? []).includes(from.objectId) && (spec.coverage?.objectIds ?? []).includes(to.objectId);
584
+ return {id: r.id, subjectId: from?.objectId, attachmentId: to?.objectId, t0: from && to ? Math.max(0, Math.min(from.start, to.start) - 1 / spec.fps) : 0,
585
+ t1: from && to ? Math.max(from.end, to.end) : 0, rigid: r.motionGate === 'rigid-feedback', timelineRelay: {fromAction: r.fromAction, toAction: r.toAction, fromRange: from ? [from.start, from.end] : null, toRange: to ? [to.start, to.end] : null}, viewport: spec.viewport,
586
+ ...(r.trigger ? {trigger:r.trigger} : r.triggerTime != null ? {triggerTime:r.triggerTime} : {}),
587
+ valid, anchorReason: valid ? null : '接力没有指向两个不同且已覆盖的生产动作对象。'};
588
+ });
589
+ const anticipations = actions.filter(a => a.motionGate === 'anticipation').map(a => ({id: a.id, subjectId: a.objectId, t0: a.start, t1: a.end, reveal: a.kind === 'reveal', rigid: a.rigid === true, timelineAction: a.id, viewport: spec.viewport,
590
+ valid: (spec.coverage?.objectIds ?? []).includes(a.objectId), anchorReason: '预备动作对象不在生产 coverage 中。'}));
591
+ const origin = {follows: follows.length ? 'timeline-relays' : 'legacy-motionCast', anticipations: anticipations.length ? 'timeline-actions' : 'legacy-motionCast', mainContentIds: spec.coverage?.mainContentIds ? 'coverage' : 'legacy-motionCast'};
592
+ return {...cast, ...(follows.length ? {follows} : {}), ...(anticipations.length ? {anticipations} : {}), mainContentIds: spec.coverage?.mainContentIds ?? cast.mainContentIds, origin};
593
+ }
594
+
595
+ function fixedPose(frame) {
596
+ if (frame.camera) {
597
+ const {cx,cy,z} = frame.camera;
598
+ if ([cx,cy,z].every(Number.isFinite) && z > 0) return [cx,cy,z];
599
+ }
600
+ const c = frame.camera3d;
601
+ if (c && [c.position,c.right,c.down,c.forward].every(v => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite)) &&
602
+ [c.focalLength,c.viewport?.width,c.viewport?.height].every(v => Number.isFinite(v) && v > 0)) {
603
+ return [...c.position,...c.right,...c.down,...c.forward,c.focalLength,c.viewport.width,c.viewport.height];
604
+ }
605
+ throw Error('固定镜头的实际相机姿态未暴露。');
606
+ }
607
+
608
+ export function evaluateSpec(spec, {stillness, gates = DEFAULT_GATES, baseDir = process.cwd()} = {}) {
609
+ const cast = deriveMotionCast(spec);
610
+ const windows = cast.cameraWindows?.length ? cast.cameraWindows : [{id: 'all', t0: 0, t1: spec.duration}];
611
+ const fps = spec.fps;
612
+ let cameraError = null;
613
+ let sceneCuts = new Set();
614
+ const allMoves = [];
615
+ const windowStats = [];
616
+ const fixedDrift = [];
617
+ let measuredFixedIntervals = 0;
618
+ try {
619
+ const {frames:cuts,gaps} = cameraCutFrames(spec,baseDir);
620
+ if (gaps.length) throw Error(gaps.join(' '));
621
+ sceneCuts = cuts;
622
+ for (const w of windows) {
623
+ if (![w.t0,w.t1].every(Number.isFinite) || w.t0 < 0 || w.t1 > spec.duration || w.t1 <= w.t0) throw Error('镜头窗口无效:' + w.id);
624
+ const cache = new Map();
625
+ const at = t => {
626
+ const key = t;
627
+ if (!cache.has(key)) cache.set(key, spec.frameAt(key, {windowId: w.id, t0: w.t0, t1: w.t1}));
628
+ return cache.get(key);
629
+ };
630
+ const start = Math.ceil(w.t0*fps-1e-8), end = Math.ceil(w.t1*fps-1e-8);
631
+ const boundaries = [start,...[...cuts].filter(i => start < i && i < end).sort((a,b)=>a-b),end];
632
+ if (end <= start) throw Error('镜头窗口没有编码帧:' + w.id);
633
+ for (let j=0; j+1<boundaries.length; j++) {
634
+ const first = boundaries[j], last = boundaries[j+1]-1;
635
+ if (w.role === 'fixed') {
636
+ // Adjacent fixed windows also share a pose unless there is an actual cut.
637
+ const previousFixed = windows.some(prev => prev.role === 'fixed' && Math.abs(prev.t1-w.t0)<1e-8);
638
+ const compareFrom = first === start && previousFixed && !cuts.has(first) && first > 0 ? first-1 : first;
639
+ const reference = fixedPose(at(compareFrom/fps));
640
+ let firstDrift = null, lastDrift = null;
641
+ for (let i=compareFrom+1; i<=last; i++) {
642
+ const current = fixedPose(at(i/fps));
643
+ if (current.length !== reference.length) throw Error('固定窗口的相机坐标类型发生变化:'+w.id);
644
+ if (current.some((v,k) => Math.abs(v-reference[k]) > 1e-7)) {
645
+ firstDrift ??= i;
646
+ lastDrift = i;
647
+ }
648
+ }
649
+ measuredFixedIntervals += last-compareFrom;
650
+ if (firstDrift !== null) fixedDrift.push({id:w.id,firstDriftFrame:firstDrift,lastDriftFrame:lastDrift,
651
+ start:firstDrift/fps,end:lastDrift/fps,fps,reviewFrames:[...new Set([
652
+ Math.max(compareFrom,firstDrift-1),firstDrift,Math.min(last,firstDrift+1),lastDrift,Math.min(last,lastDrift+1)])]});
653
+ windowStats.push({id:w.id,role:'fixed',firstFrame:first,lastFrame:last,fixedIntervals:last-compareFrom});
654
+ continue;
655
+ }
656
+ const samples = [];
657
+ for (let i=first;i<=last;i++) {const t=i/fps; samples.push({t,camera:at(t)?.camera});}
658
+ if (samples.some(s => !s.camera || ![s.camera.cx,s.camera.cy,s.camera.z].every(Number.isFinite) || s.camera.z <= 0))
659
+ throw new Error(`窗口 ${w.id} 的 frameAt 没有有效的二维 camera。`);
660
+ const measured = measureMoves(samples.map(s => ({t: s.t, ...s.camera})), fps, gates, t => {
661
+ const frame = at(t);
662
+ if (!frame?.camera) throw new Error(`frameAt(${t}) 没有 camera。`);
663
+ return frame.camera;
664
+ });
665
+ if (measured.error) throw new Error(measured.error);
666
+ const large = measured.moves.filter(m => m.arcPx + 1e-9 >= gates.largeArcPx);
667
+ windowStats.push({
668
+ id: w.id, t0: first/fps, t1: last/fps, largeCount: large.length,
669
+ medianMeanPxPerSec: round(median(large.map(m => m.mean)), 0),
670
+ slowestMeanPxPerSec: large.length ? round(Math.min(...large.map(m => m.mean)), 1) : null,
671
+ });
672
+ for (const m of measured.moves) allMoves.push({...m, window: w.id});
673
+ }
674
+ }
675
+ } catch (err) {
676
+ cameraError = String(err.message || err);
677
+ }
678
+ const readings = bindList(cast.reading, baseDir).filter(r => r.valid);
679
+ const roles = cast.cameraRoles ?? null;
680
+ let gate2;
681
+ if (fixedDrift.length) gate2 = {status:'未通过',judgment:'hard-gate',reasons:['实际相机在声明的固定窗口发生变化。',...(cameraError?[cameraError]:[])],measured:{fixedDrift}};
682
+ else if (cameraError) gate2 = {status:'无法测量',reasons:[cameraError],measured:{}};
683
+ else if (windows.every(w=>w.role==='fixed')) gate2 = measuredFixedIntervals
684
+ ? {status:'通过',judgment:'hard-gate',reasons:[],measured:{measuredFixedIntervals}}
685
+ : {status:'无法测量',reasons:['固定窗口内没有相邻的编码帧。'],measured:{}};
686
+ else gate2 = scoreCamera({moves:allMoves,duration:spec.duration,gates,roles,readings,windowStats});
687
+ gate2.measured.windows = windowStats;
688
+
689
+ const follows = cast.origin.follows === 'timeline-relays' ? cast.follows : bindList(cast.follows, baseDir);
690
+ let gate3;
691
+ if (!follows.length) gate3 = {status: '无法测量', reasons: ['没有要测启动时差的生产接力标记或旧适配器条目。'], measured: {}};
692
+ else if (follows.some(f => !f.valid)) gate3 = {status: '无法测量', reasons: follows.filter(f => !f.valid).map(f => f.anchorReason), measured: {}};
693
+ else {
694
+ const parts = [];
695
+ for (const beat of follows) {
696
+ try {
697
+ const samples = sampleFrames(spec.frameAt, beat.t0, beat.t1, gates.clockFps);
698
+ parts.push(scoreFollow(samples, beat, gates));
699
+ } catch (err) {
700
+ parts.push({id: beat.id, status: '无法测量', reasons: [String(err.message || err)]});
701
+ }
702
+ }
703
+ gate3 = mergeGate(parts);
704
+ }
705
+
706
+ // A passing selected relay is only a selected measurement. Compare against all
707
+ // production relationships and actual parent/part changes before aggregating it.
708
+ let actionCoverage=null;
709
+ if(spec.actions&&spec.coverage)try{
710
+ actionCoverage=inspectActionCoverage(spec,sampleFrames(spec.frameAt,0,spec.duration,spec.fps),sceneCuts);
711
+ const followCoverage=actionCoverage.follow;
712
+ gate3.measured={...(gate3.measured??{}),coverage:followCoverage};
713
+ const missing=[...followCoverage.uncoveredRelayIds.map(id=>'未测生产接力 '+id),...followCoverage.relatedActionCandidates.map(r=>'尚未辨认父部件关系 '+r.parentAction+' → '+r.partAction)];
714
+ if(missing.length){if(gate3.status!=='未通过')gate3.status='无法测量';gate3.reasons=[...(gate3.reasons??[]),...missing];}
715
+ else if(!follows.length && Array.isArray(spec.relays) && !spec.relays.length){
716
+ const proof=spec.coverage.notApplicable?.relays;
717
+ if(proof?.reason && anchorOk(proof,baseDir).valid &&
718
+ spec.sourceFiles?.some(f=>path.resolve(baseDir,f)===path.resolve(baseDir,proof.sourceFile))){
719
+ gate3={status:'不适用',reasons:[proof.reason],measured:{coverage:followCoverage,basis:proof}};
720
+ }
721
+ }
722
+ }catch(err){if(gate3.status!=='未通过')gate3.status='无法测量';gate3.reasons=[...(gate3.reasons??[]),'动作覆盖无法建立:'+String(err.message??err)];}
723
+
724
+ const anticipations = cast.origin.anticipations === 'timeline-actions' ? cast.anticipations : bindList(cast.anticipations, baseDir);
725
+ let gate4;
726
+ if (!anticipations.length) gate4 = {status: '无法测量', reasons: ['没有声明要检查的主体位移或主要物件揭示。'], measured: {}};
727
+ else if (anticipations.some(a => !a.valid)) gate4 = {status: '无法测量', reasons: anticipations.filter(a => !a.valid).map(a => a.anchorReason), measured: {}};
728
+ else {
729
+ const parts = [];
730
+ for (const beat of anticipations) {
731
+ try {
732
+ const lead = gates.anticipationMaxFrames / gates.clockFps;
733
+ const samples = sampleFrames(spec.frameAt, Math.max(0, beat.t0 - lead), beat.t1, gates.clockFps);
734
+ parts.push(scoreAnticipation(samples, beat, gates));
735
+ } catch (err) {
736
+ parts.push({id: beat.id, status: '无法测量', reasons: [String(err.message || err)]});
737
+ }
738
+ }
739
+ gate4 = mergeGate(parts);
740
+ gate4.reference = {ampPx: EP05_REFERENCE.anticipationAmpPx, deform: EP05_REFERENCE.deform};
741
+ }
742
+
743
+ let gate5;
744
+ if (!cast.mainContentIds?.length) {
745
+ gate5 = {status: '无法测量', reasons: ['没有声明主要内容对象,不能算外接框。'], measured: {}};
746
+ } else try {
747
+ const samples = sampleFrames(spec.frameAt, 0, spec.duration, Math.min(fps, 30));
748
+ const emptyMood = bindList(cast.emptyMood, baseDir);
749
+ gate5 = scoreComposition(samples, {...cast, emptyMood}, gates);
750
+ } catch (err) {
751
+ gate5 = {status: '无法测量', reasons: [String(err.message || err)], measured: {}};
752
+ }
753
+
754
+ // Only declared reading windows (text actually being read) and user-confirmed exceptions are exempt.
755
+ const exceptions = bindList(cast.stillExceptions ?? cast.freezeExceptions, baseDir);
756
+ const readingWindows = bindList(cast.reading, baseDir).filter(r => r.valid);
757
+ const gate1 = stillness
758
+ ? scoreStillness({area: stillness.area, fps: stillness.fps, comp: stillness.comp, cuts: stillness.cuts ?? null, allowedCuts: [...sceneCuts].map(i => i / fps),
759
+ readings: readingWindows, exceptions, gates: stillGates(gates)})
760
+ : {status: '无法测量', reasons: ['没有成片的逐帧变化数据。'], measured: {}};
761
+
762
+ const gatesOut = [
763
+ {id: 1, name: '感知静止', ...gate1},
764
+ {id: 2, name: '声明窗口的镜头数值', ...gate2},
765
+ {id: 3, name: '声明对象的启动时差', ...gate3},
766
+ {id: 4, name: '触发动作的预备时长', ...gate4},
767
+ {id: 5, name: '稳定主内容外接框宽度', ...gate5},
768
+ ];
769
+ for(const g of gatesOut)g.judgment=g.judgment??([1,3].includes(g.id)?'hard-gate':'diagnostic');
770
+ const exitCode = gatesOut.some(g => g.status === '未通过') ? 2 : gatesOut.some(g => !['通过','诊断','不适用'].includes(g.status)) ? 1 : 0;
771
+ return {
772
+ reportVersion: 2,
773
+ status: exitCode === 0 ? '硬要求已测,诊断待人工判断' : exitCode === 2 ? '硬要求未满足' : '数值测量不完整',
774
+ exitCode,
775
+ visualAcceptance: 'not-assessed',
776
+ actionCoverage,
777
+ scope: {markerOrigin: cast.origin, componentSemantics: 'not-assessed', weight: 'not-assessed', note: '数值结果仅限报告中的对象、动作与窗口;没有测到问题不代表整体质量或部件表达通过。'},
778
+ gates: gatesOut,
779
+ reference: EP05_REFERENCE,
780
+ thresholds: gates,
781
+ };
782
+ }
783
+
784
+ function fileLock(file) {
785
+ const resolved = fs.realpathSync(file), bytes = fs.readFileSync(resolved);
786
+ return {path: resolved, bytes: bytes.length, sha256: crypto.createHash('sha256').update(bytes).digest('hex')};
787
+ }
788
+
789
+ // One entry for old and new adapters: numeric measurements plus the existing
790
+ // source/video-bound engineering audit when that production contract is exposed.
791
+ export function evaluateMotion(spec, {stillness, gates = DEFAULT_GATES, baseDir = process.cwd(), adapterFile, video, requireVideo = !!video} = {}) {
792
+ const hasAuditContract = !!(spec.coverage || spec.sourceFiles || spec.actions);
793
+ const coverage = {mode: hasAuditContract ? 'production-audit' : 'legacy-declared-numeric-scope', internalProcess: 'unexposed', scriptSemantics: 'not-assessed'};
794
+ let inputLocks;
795
+ // Capture these before the first frameAt call, not after numeric sampling.
796
+ // The later audit must bind the very same versions.
797
+ try {
798
+ if (video && spec.videoFile && fs.realpathSync(path.resolve(baseDir, spec.videoFile)) !== fs.realpathSync(video)) throw new Error('适配器 videoFile 与本次 --video 不同,不能混用证据。');
799
+ const sources = [...new Set([...(spec.sourceFiles ?? []), ...(adapterFile ? [adapterFile] : [])].map(f => fs.realpathSync(path.resolve(baseDir, f))))];
800
+ const selectedVideo = video ?? (spec.videoFile ? path.resolve(baseDir, spec.videoFile) : null);
801
+ inputLocks = {tool: fileLock(fileURLToPath(import.meta.url)), observationTool:fileLock(fileURLToPath(new URL('./motion-observation.cjs',import.meta.url))),sources: sources.map(fileLock), video: selectedVideo ? fileLock(selectedVideo) : null};
802
+ } catch (err) {
803
+ return {status: '测量不完整', exitCode: 1, visualAcceptance: 'not-assessed', coverage, gates: [], engineeringAudit: {status: 'incomplete', visualAcceptance: 'not-assessed', coverageGaps: [String(err.message || err)]}};
804
+ }
805
+ const result = evaluateSpec(spec, {stillness, gates, baseDir});
806
+ result.coverage = coverage;
807
+ result.locks = inputLocks;
808
+ function checkInputLocks() {
809
+ for (const [kind, lock] of [...inputLocks.sources.map(lock => ['Source', lock]),['Observation tool',inputLocks.observationTool], ...(inputLocks.video ? [['Video', inputLocks.video]] : [])]) {
810
+ let current;
811
+ try { current = fileLock(lock.path); } catch { throw new Error(`${kind} changed while sampling: ${lock.path} is no longer readable`); }
812
+ if (current.sha256 !== lock.sha256 || current.path !== lock.path) throw new Error(`${kind} changed while sampling: ${lock.path}`);
813
+ }
814
+ }
815
+ function rejectChangedInputs(err) {
816
+ const reason = String(err.message || err);
817
+ result.engineeringAudit = {status: 'incomplete', visualAcceptance: 'not-assessed', coverageGaps: [reason]};
818
+ result.locks = inputLocks;
819
+ result.gates = result.gates.map(g => ({id: g.id, name: g.name, status: '无法测量', reasons: [reason + '; mixed-version numeric measurements discarded.'], measured: {}}));
820
+ result.exitCode = 1;
821
+ result.status = '测量不完整';
822
+ return result;
823
+ }
824
+ try { checkInputLocks(); } catch (err) { return rejectChangedInputs(err); }
825
+ if (hasAuditContract) {
826
+ try {
827
+ const audit = auditMotion({...spec, ...(video ? {videoFile: video} : {})}, {baseDir, adapterFile, requireVideo});
828
+ if (audit.locks.sources.length !== inputLocks.sources.length || inputLocks.sources.some(lock => !audit.locks.sources.some(a => a.path === lock.path && a.sha256 === lock.sha256))) throw new Error('Source changed between numeric sampling and engineering audit bindings.');
829
+ if (audit.locks.video?.path !== inputLocks.video?.path || audit.locks.video?.sha256 !== inputLocks.video?.sha256) throw new Error('Video changed between numeric sampling and engineering audit bindings.');
830
+ result.engineeringAudit = audit;
831
+ result.locks = {...audit.locks, sources: inputLocks.sources, video: inputLocks.video, gatesTool: inputLocks.tool};
832
+ result.coverage.internalProcess = audit.processCoverage;
833
+ if (audit.findings.length) result.exitCode = 2;
834
+ else if (audit.status === 'incomplete' && result.exitCode !== 2) result.exitCode = 1;
835
+ } catch (err) {
836
+ if (/Source changed|Video changed/.test(String(err.message || err))) return rejectChangedInputs(err);
837
+ result.engineeringAudit = {status: 'incomplete', visualAcceptance: 'not-assessed', coverageGaps: [String(err.message || err)]};
838
+ if (result.exitCode !== 2) result.exitCode = 1;
839
+ }
840
+ } else {
841
+ result.coverage.limitations = ['Legacy motionCast checks only its selected IDs and windows.', 'Internal parts, script promises and production-source association are not covered.'];
842
+ }
843
+ try { checkInputLocks(); } catch (err) { return rejectChangedInputs(err); }
844
+ result.status = result.exitCode === 0 ? '硬要求已测,诊断待人工判断' : result.exitCode === 2 ? '发现硬要求失败或工程待核问题' : '测量不完整';
845
+ return result;
846
+ }
847
+
848
+ export async function loadAdapter(file, input) {
849
+ const abs = path.resolve(file);
850
+ if (abs.endsWith('.mjs')) {
851
+ const mod = await import(pathToFileURL(abs).href);
852
+ const fn = mod.exportAudit ?? mod.default?.exportAudit;
853
+ if (typeof fn !== 'function') throw new Error('适配器没有 exportAudit()。');
854
+ return {spec: await fn(input), file: abs};
855
+ }
856
+ const req = createRequire(abs);
857
+ const mod = req(abs);
858
+ const fn = mod.exportAudit ?? mod.default?.exportAudit;
859
+ if (typeof fn !== 'function') throw new Error('适配器没有 exportAudit()。');
860
+ return {spec: await fn(input), file: abs};
861
+ }
862
+
863
+ // The production entry renders a frozen source directory. Resolve the receipt
864
+ // before importing code, then recheck its locks after sampling and decoding.
865
+ function readRenderManifest(file, adapter, video) {
866
+ const manifestPath = fs.realpathSync(file);
867
+ const bytes = fs.readFileSync(manifestPath);
868
+ const lock = {path:manifestPath,bytes:bytes.length,sha256:crypto.createHash('sha256').update(bytes).digest('hex')};
869
+ const manifest = JSON.parse(bytes.toString('utf8'));
870
+ const dir = path.dirname(lock.path);
871
+ const sourceDir = path.join(dir, 'source');
872
+ if (!Array.isArray(manifest.sources) || !manifest.sources.length ||
873
+ !Array.isArray(manifest.omitIds) || manifest.omitIds.some(id => typeof id !== 'string') ||
874
+ !manifest.input || typeof manifest.input !== 'object' || Array.isArray(manifest.input)) {
875
+ throw Error('渲染清单缺少实际输入、删层参数或源码快照。');
876
+ }
877
+ const verifyFile = (root, entry) => {
878
+ if (!entry || typeof entry.name !== 'string' || path.isAbsolute(entry.name) ||
879
+ entry.name.split(/[\\/]/).some(part => !part || part === '..' || part === '.')) throw Error('渲染清单文件路径无效。');
880
+ const actual = fileLock(path.resolve(root, entry.name));
881
+ const relative = path.relative(fs.realpathSync(root), actual.path);
882
+ if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative) || actual.sha256 !== entry.sha256) {
883
+ throw Error('文件与渲染时的版本不同:' + entry.name);
884
+ }
885
+ return actual;
886
+ };
887
+ const sources = manifest.sources.map(entry => verifyFile(sourceDir, entry));
888
+ if (!sources.some(source => source.path === fs.realpathSync(adapter))) throw Error('检查适配器未绑定这次渲染的源码快照。');
889
+ const videoLock = verifyFile(dir, manifest.video);
890
+ if (videoLock.path !== fs.realpathSync(video)) throw Error('成片与渲染清单不匹配。');
891
+ return {lock, sources, videoLock, config:manifest.config, input:{sceneInput:manifest.input, omitIds:manifest.omitIds, videoFile:videoLock.path}};
892
+ }
893
+
894
+ function parseArgs(argv) {
895
+ const out = {};
896
+ for (let i = 0; i < argv.length; i++) {
897
+ const key = argv[i];
898
+ if (!key.startsWith('--')) continue;
899
+ const name = key.slice(2);
900
+ const value = argv[i + 1];
901
+ if (value == null || value.startsWith('--')) out[name] = true;
902
+ else { out[name] = value; i++; }
903
+ }
904
+ return out;
905
+ }
906
+
907
+ function readGates(file) {
908
+ if (!file) return {...DEFAULT_GATES};
909
+ const extra = JSON.parse(fs.readFileSync(file, 'utf8'));
910
+ return {...DEFAULT_GATES, ...extra};
911
+ }
912
+
913
+ const HELP = `node scripts/motion-gates.mjs --adapter <adapter.mjs|cjs> --video <preview.mp4> --out <report.json> [--render-manifest <render-manifest.json>] [--gates <overrides.json>]
914
+ 报告 reportVersion:2。第 1 项为感知静止、构图多久没变和一帧换场(与 scripts/stillness.mjs 同一算法),静止和构图只豁免登记的读字窗口和用户确认的例外;一帧换场只放行带来源依据的 role:'cut', scope:'scene' 检查点,它们只能用在章与章之间或用户确认的断点。固定镜头由 motionCast.cameraWindows 的 role:'fixed' 声明并逐帧核对,实际姿态漂移将记为硬失败;镜头固定只说明机位没动,画面是否在推进由第 1 项判断。其余相机风格、预备时长和构图只作诊断。整场硬切用现有带来源依据的 role:'cut', scope:'scene' 检查点,在切点两侧分别计算。
915
+ 退出码:0 硬要求已测且诊断数据完整,待人工判断;2 硬要求失败或工程审计待核问题;1 输入或覆盖不完整。都不是视觉验收。
916
+ 优先复用 actions[].motionGate / relays[].motionGate 与 coverage.mainContentIds。完整生产适配器同步运行 motion-audit 并绑定源码/成片 SHA-256;旧 motionCast 只保留有限数值检测。`;
917
+
918
+ export async function main(argv = process.argv.slice(2)) {
919
+ const args = parseArgs(argv);
920
+ if (args.help || !args.adapter || !args.video || !args.out) {
921
+ console.log(HELP);
922
+ return args.help ? 0 : 1;
923
+ }
924
+ const gates = readGates(args.gates);
925
+ const video = path.resolve(args.video);
926
+ if (!fs.existsSync(video) || !fs.statSync(video).isFile()) {
927
+ const report = {status: '无法测量', exitCode: 1, reasons: [`找不到预览视频 ${video}`]};
928
+ fs.mkdirSync(path.dirname(path.resolve(args.out)), {recursive: true});
929
+ fs.writeFileSync(args.out, JSON.stringify(report, null, 2));
930
+ return 1;
931
+ }
932
+ const beforeDecode = fileLock(video);
933
+ let stillness = null;
934
+ let stillnessError = null;
935
+ try {
936
+ stillness = measureStillness(video, {ffmpeg: args.ffmpeg || 'ffmpeg', gates: stillGates(gates)});
937
+ } catch (err) {
938
+ stillnessError = String(err.message || err);
939
+ }
940
+ let spec;
941
+ let adapterFile;
942
+ let receipt;
943
+ try {
944
+ receipt = args['render-manifest'] ? readRenderManifest(args['render-manifest'], args.adapter, video) : null;
945
+ const loaded = await loadAdapter(args.adapter, receipt?.input);
946
+ spec = loaded.spec;
947
+ adapterFile = loaded.file;
948
+ if (spec?.schemaVersion !== 1) throw new Error('schemaVersion 必须为 1。');
949
+ if (!(spec.fps > 0) || !(spec.duration > 0) || typeof spec.frameAt !== 'function') throw new Error('exportAudit() 缺少 fps、duration 或 frameAt。');
950
+ if (receipt) {
951
+ const {config} = receipt;
952
+ if (config?.fps !== spec.fps || config?.duration !== spec.duration || config?.width !== spec.viewport?.width || config?.height !== spec.viewport?.height) {
953
+ throw Error('适配器的帧率、时长或画幅与渲染清单不匹配。');
954
+ }
955
+ spec = {...spec, sourceFiles:[...new Set([...(spec.sourceFiles ?? []), ...receipt.sources.map(s => s.path)])]};
956
+ }
957
+ } catch (err) {
958
+ const report = {status: '无法测量', exitCode: 1, visualAcceptance:'not-assessed', gates:[], reasons: [String(err.message || err)]};
959
+ fs.mkdirSync(path.dirname(path.resolve(args.out)), {recursive: true});
960
+ fs.writeFileSync(args.out, JSON.stringify(report, null, 2));
961
+ return 1;
962
+ }
963
+ const result = evaluateMotion(spec, {stillness, gates, baseDir: path.dirname(adapterFile), adapterFile, video});
964
+ if (receipt && result.locks) result.locks.renderManifest = receipt.lock;
965
+ const expected = [beforeDecode, ...(receipt ? [receipt.lock, receipt.videoLock, ...receipt.sources] : [])];
966
+ if (!expected.every(lock => {
967
+ try { return fileLock(lock.path).sha256 === lock.sha256; } catch { return false; }
968
+ })) {
969
+ const reason = '取证期间,源码、渲染清单或成片版本已变化,须对同一版本重新取证。';
970
+ fs.mkdirSync(path.dirname(path.resolve(args.out)), {recursive:true});
971
+ fs.writeFileSync(args.out, JSON.stringify({status:'测量不完整', exitCode:1, visualAcceptance:'not-assessed', gates:[], reasons:[reason]}, null, 2));
972
+ return 1;
973
+ }
974
+ if (stillness) result.stillnessEvidence = {videoAssociation: 'decoded-current-video', videoSha256: result.locks?.video?.sha256 ?? null, sampleFps: stillness.fps};
975
+ if (stillness && Math.abs(stillness.duration - spec.duration) > 1 / 30 + 0.02) {
976
+ stillnessError = '静止检测时长与适配器时长不一致,不能混用。';
977
+ }
978
+ if (stillnessError) {
979
+ result.gates[0] = {id: 1, name: '感知静止', status: '无法测量', reasons: [stillnessError], measured: {}};
980
+ result.exitCode = result.exitCode === 2 || result.gates.some(g => g.status === '未通过') ? 2 : 1;
981
+ result.status = result.exitCode === 2 ? '发现约束失败或待核问题' : '测量不完整';
982
+ }
983
+ result.video = video;
984
+ result.adapter = adapterFile;
985
+ fs.mkdirSync(path.dirname(path.resolve(args.out)), {recursive: true});
986
+ fs.writeFileSync(args.out, JSON.stringify(result, null, 2));
987
+ const brief = result.gates.map(g => `${g.id}:${g.status}`).join(' ');
988
+ console.log(`${result.status};视觉验收未执行;范围 ${result.coverage.mode}。 ${brief}`);
989
+ return result.exitCode;
990
+ }
991
+
992
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
993
+ main().then(code => { process.exitCode = code; }).catch(err => {
994
+ console.error(err?.stack || err);
995
+ process.exitCode = 1;
996
+ });
997
+ }