@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,204 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Small production SVG recorder and conservative observation helpers. No runtime dependency.
3
+ // Supported proof: filled rectangles/simple polygons, axis-aligned parent transforms and rectangular clips,
4
+ // fully opaque rectangular foreground paint. Raw SVG/unsupported paint remains unknown.
5
+ (function(root,factory){const api=factory();if(typeof module==='object'&&module.exports)module.exports=api;else root.MotionObservation=api;})(typeof globalThis!=='undefined'?globalThis:this,function(){
6
+ 'use strict';
7
+ const EPS=1e-8,I=[1,0,0,1,0,0];
8
+ // In-process recorder provenance, not a caller-fillable certification field.
9
+ // A serialized/copied observation has no production record and must be re-observed.
10
+ const recordedObservations=new WeakMap(),recordedFrames=new WeakMap();
11
+ const geometryKey=o=>JSON.stringify([o.id,o.x,o.y,o.width,o.height,o.opacity,o.rotation??0,o.parentId??null]);
12
+ function recordedFrameState(frame){
13
+ const record=recordedFrames.get(frame);
14
+ if(!record)return{status:'unverified',reason:'no-shared-production-record'};
15
+ if(frame.svg!==record.svg||JSON.stringify(frame.renderedObjectIds)!==record.ids||frame.objects.length!==record.objects.length||frame.objects.some((o,i)=>o.observation!==record.objects[i].observation||geometryKey(o)!==record.objects[i].key))return{status:'unverified',reason:'production-record-changed-after-render'};
16
+ return{status:'recorded',reason:'same-production-submissions',viewport:{...record.viewport}};
17
+ }
18
+ const finite=(x,label)=>{if(!Number.isFinite(x))throw Error('Non-finite '+label);return x;};
19
+ const esc=x=>String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&apos;'}[c]));
20
+ const multiply=(a,b)=>[a[0]*b[0]+a[2]*b[1],a[1]*b[0]+a[3]*b[1],a[0]*b[2]+a[2]*b[3],a[1]*b[2]+a[3]*b[3],a[0]*b[4]+a[2]*b[5]+a[4],a[1]*b[4]+a[3]*b[5]+a[5]];
21
+ const point=(m,p)=>[m[0]*p[0]+m[2]*p[1]+m[4],m[1]*p[0]+m[3]*p[1]+m[5]];
22
+ const axis=m=>Math.abs(m[1])<EPS&&Math.abs(m[2])<EPS;
23
+ const rectPoints=r=>[[r.x,r.y],[r.x+r.width,r.y],[r.x+r.width,r.y+r.height],[r.x,r.y+r.height]];
24
+ const box=ps=>{if(!ps.length)return{x:0,y:0,width:0,height:0};const xs=ps.map(p=>p[0]),ys=ps.map(p=>p[1]),x=Math.min(...xs),y=Math.min(...ys);return{x,y,width:Math.max(...xs)-x,height:Math.max(...ys)-y};};
25
+ const area=p=>Math.abs(p.reduce((s,a,i)=>{const b=p[(i+1)%p.length];return s+a[0]*b[1]-b[0]*a[1];},0))/2;
26
+ // Shoelace/clipping assumes a simple boundary; self-intersections can cancel actual painted area.
27
+ function simplePolygon(ps){
28
+ if(area(ps)<=EPS)return false;
29
+ const cross=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
30
+ const on=(a,b,p)=>Math.abs(cross(a,b,p))<=EPS&&p[0]>=Math.min(a[0],b[0])-EPS&&p[0]<=Math.max(a[0],b[0])+EPS&&p[1]>=Math.min(a[1],b[1])-EPS&&p[1]<=Math.max(a[1],b[1])+EPS;
31
+ for(let i=0;i<ps.length;i++){
32
+ const a=ps[i],b=ps[(i+1)%ps.length];if(Math.hypot(b[0]-a[0],b[1]-a[1])<=EPS)return false;
33
+ for(let j=i+1;j<ps.length;j++){
34
+ if(j===i+1||(i===0&&j===ps.length-1))continue;
35
+ const c=ps[j],d=ps[(j+1)%ps.length],abC=cross(a,b,c),abD=cross(a,b,d),cdA=cross(c,d,a),cdB=cross(c,d,b);
36
+ if(((abC>EPS&&abD< -EPS)||(abC< -EPS&&abD>EPS))&&((cdA>EPS&&cdB< -EPS)||(cdA< -EPS&&cdB>EPS))||on(a,b,c)||on(a,b,d)||on(c,d,a)||on(c,d,b))return false;
37
+ }
38
+ }
39
+ return true;
40
+ }
41
+ const intersects=(a,b)=>a.width>0&&a.height>0&&b.width>0&&b.height>0&&a.x<b.x+b.width&&a.x+a.width>b.x&&a.y<b.y+b.height&&a.y+a.height>b.y;
42
+ function half(poly,index,value,keepGreater){
43
+ if(!poly.length)return[];const out=[],inside=p=>keepGreater?p[index]>=value-EPS:p[index]<=value+EPS;
44
+ for(let i=0;i<poly.length;i++){const a=poly[i],b=poly[(i+1)%poly.length],ia=inside(a),ib=inside(b);if(ia)out.push(a);if(ia!==ib){const q=(value-a[index])/(b[index]-a[index]);out.push([a[0]+q*(b[0]-a[0]),a[1]+q*(b[1]-a[1])]);}}
45
+ return out;
46
+ }
47
+ function clipPolygon(p,r){return half(half(half(half(p,0,r.x,true),0,r.x+r.width,false),1,r.y,true),1,r.y+r.height,false);}
48
+ function subtractRect(p,r){
49
+ let rest=p;const out=[];for(const [k,v,greater]of [[0,r.x,true],[0,r.x+r.width,false],[1,r.y,true],[1,r.y+r.height,false]]){const exterior=half(rest,k,v,!greater);if(area(exterior)>EPS)out.push(exterior);rest=half(rest,k,v,greater);if(area(rest)<=EPS)break;}return out;
50
+ }
51
+ function visibleState(o,viewport={width:1920,height:1080}){
52
+ if(!o)return{state:'hidden',reason:'not-drawn-or-empty'};
53
+ const observation=o.observation,record=observation&&recordedObservations.get(observation);
54
+ if(record&&record.key===geometryKey(o)&&record.viewport.width===viewport.width&&record.viewport.height===viewport.height)return record.observation;
55
+ if((o.opacity??1)<=0)return{state:'hidden',reason:'not-drawn-or-empty'};
56
+ // An empty author bbox does not prove empty paint (raw SVG can fill the screen).
57
+ // Recorded primitive emptiness was resolved above by the actual draw geometry.
58
+ if(o.width<=0||o.height<=0)return{state:'unknown',reason:'unverified-empty-bounds'};
59
+ const on=intersects(o,{x:0,y:0,...viewport});
60
+ if(!on){if(Math.abs(o.rotation??0)>EPS)return{state:'unknown',reason:'unresolved-rotation'};return{state:'hidden',reason:'outside-viewport'};}
61
+ return{state:'unknown',reason:observation?'unverified-author-observation':'bbox-only-no-painted-visibility'};
62
+ }
63
+ function createObservedScene({width=1920,height=1080,camera}={}){
64
+ finite(width,'width');finite(height,'height');if(width<=0||height<=0)throw Error('Invalid viewport');
65
+ const cam=camera?{...camera}:null,cm=cam?[cam.z,0,0,cam.z,width/2-cam.cx*cam.z,height/2-cam.cy*cam.z]:I;
66
+ cm.forEach(v=>finite(v,'camera'));if(cam&&cam.z<=0)throw Error('Invalid camera zoom');
67
+ const nodes=[],byId=new Map();
68
+ function add(type,s,paint){
69
+ if(!s||typeof s.id!=='string'||!s.id||byId.has(s.id))throw Error('Missing/duplicate production object ID');
70
+ const parent=s.parentId?byId.get(s.parentId):null;if(s.parentId&&!parent)throw Error('Parent must be submitted before child: '+s.id);
71
+ const transform=s.transform??I;if(!Array.isArray(transform)||transform.length!==6)throw Error('Expected six-number affine transform');transform.forEach(v=>finite(v,'transform'));
72
+ const local=type==='polygon'?s.points:rectPoints({x:s.x??0,y:s.y??0,width:s.width??0,height:s.height??0});
73
+ if(!Array.isArray(local)||local.length<3||local.some(p=>!Array.isArray(p)||p.length!==2||p.some(v=>!Number.isFinite(v))))throw Error('Invalid production geometry');
74
+ if(type==='polygon'&&!simplePolygon(local))throw Error('Unsupported self-intersecting or degenerate polygon; use raw() with conservative painted bounds');
75
+ const geometry=box(local.map(p=>point(transform,p))),matrix=multiply(parent?.matrix??cm,transform),ps=local.map(p=>point(matrix,p)),bounds=box(ps);
76
+ const ownOpacity=s.drawn===false?0:(s.opacity??1);finite(ownOpacity,'opacity');if(ownOpacity<0||ownOpacity>1)throw Error('Opacity outside 0..1');
77
+ const opacity=ownOpacity*(parent?.opacity??1),clips=[...(parent?.clips??[])];
78
+ if(s.clip){const c=s.clip;for(const k of ['x','y','width','height'])finite(c[k],'clip.'+k);if(c.width<0||c.height<0)throw Error('Negative clip extent');clips.push({local:{...c},matrix:[...matrix],bounds:box(rectPoints(c).map(p=>point(matrix,p))),supported:axis(matrix)});}
79
+ const style=type==='raw'?null:{fill:'#000',...paint},fill=style?.fill;
80
+ if(style&&Object.keys(style).some(k=>!['fill','stroke','strokeWidth','fillOpacity','strokeLinejoin','strokeLinecap','rx','ry','opacity'].includes(k)))throw Error('Unsupported primitive style; use raw() for arbitrary SVG');
81
+ if(type!=='raw'&&(s.filter||s.mask||s.blendMode||(style.stroke&&style.stroke!=='none'&&(style.strokeWidth??1)>0)))throw Error('Stroke/effects need conservative painted bounds; use raw() or separate filled primitives');
82
+ // Only simple literal opaque fills are proved; effects/gradients/masks are raw observations.
83
+ const simple=type!=='raw'&&typeof fill==='string'&&/^(#[0-9a-f]{3}|#[0-9a-f]{6}|black|white|red|green|blue|yellow|gray|grey)$/i.test(fill)&&!(style.rx>0||style.ry>0)&&((style.opacity??1)===1)&&!s.filter&&!s.mask&&!s.blendMode;
84
+ const supported=simple&&axis(matrix)&&clips.every(c=>c.supported),z=s.z??0;finite(z,'z');
85
+ const hotspot=s.hotspot?point(matrix,[finite(s.hotspot.x,'hotspot.x'),finite(s.hotspot.y,'hotspot.y')]):null;
86
+ const node={...s,type,style,body:type==='raw'?String(paint):null,index:nodes.length,z,local,matrix,ps,bounds,geometry,opacity,clips,supported,opaque:supported&&opacity===1&&(style?.fillOpacity??1)===1,typeRect:type==='rect',hotspot};
87
+ if(type!=='raw'&&style?.fillOpacity!==undefined){finite(style.fillOpacity,'fillOpacity');if(style.fillOpacity<0||style.fillOpacity>1)throw Error('Invalid fillOpacity');if(style.fillOpacity!==1)node.supported=false;}
88
+ nodes.push(node);byId.set(s.id,node);return s.id;
89
+ }
90
+ function finish(){
91
+ const ordered=[...nodes].sort((a,b)=>a.z-b.z||a.index-b.index),viewport={x:0,y:0,width,height};
92
+ const actualClipExtent=n=>n.clips.filter(c=>c.supported).reduce((p,c)=>clipPolygon(p,c.bounds),rectPoints(viewport));
93
+ const painted=ordered.map(n=>{let pieces=[clipPolygon(n.ps,viewport)];for(const c of n.clips)if(c.supported)pieces=pieces.map(p=>clipPolygon(p,c.bounds));pieces=pieces.filter(p=>area(p)>EPS);return{n,pieces};});
94
+ const objects=painted.map(({n,pieces},i)=>{
95
+ let remaining=pieces,uncertainFront=[],unknown=!n.supported,reason=unknown?'unsupported-paint-or-transform':'supported-painted-geometry';
96
+ if(n.opacity<=0){remaining=[];unknown=false;reason='not-drawn';}
97
+ else if(!pieces.length){unknown=false;reason='viewport-or-parent-clip-empty';}
98
+ else for(let j=i+1;j<painted.length;j++){
99
+ const front=painted[j];if(front.n.opacity<=0)continue;
100
+ // raw() is arbitrary SVG: an author's bbox neither bounds its actual paint
101
+ // nor proves an opaque fill. Do not certify the lower layer from that box.
102
+ if(front.n.type==='raw'){const extent=actualClipExtent(front.n);if(area(extent)>EPS)uncertainFront.push(box(extent));continue;}
103
+ if(!front.pieces.length)continue;
104
+ const overlap=remaining.some(p=>front.pieces.some(q=>intersects(box(p),box(q))));if(!overlap)continue;
105
+ if(front.n.opaque&&front.n.typeRect){for(const q of front.pieces)remaining=remaining.flatMap(p=>subtractRect(p,box(q))).filter(p=>area(p)>EPS);}
106
+ else{uncertainFront.push(...front.pieces.map(box));}
107
+ if(!remaining.length){unknown=false;reason='opaque-foreground-covered';break;}
108
+ }
109
+ let guaranteed=remaining;for(const r of uncertainFront)guaranteed=guaranteed.flatMap(p=>subtractRect(p,r)).filter(p=>area(p)>EPS);
110
+ if(remaining.length&&!guaranteed.length){unknown=true;reason='unsupported-or-translucent-foreground';}
111
+ // Likewise a raw layer's self-reported bbox being covered/outside cannot
112
+ // prove that every pixel it actually paints is hidden.
113
+ const rawClipped=n.type==='raw'&&area(actualClipExtent(n))<=EPS;
114
+ if(rawClipped){remaining=[];reason='actual-production-clip-empty';}
115
+ const rawUnresolved=n.type==='raw'&&n.opacity>0&&!rawClipped;
116
+ if(rawUnresolved)reason='raw-paint-bounds-unverified';
117
+ const state=rawUnresolved?'unknown':!remaining.length?'hidden':unknown?'unknown':'visible',visibleBounds=state==='visible'?box(guaranteed.flat()):null;
118
+ return{id:n.id,...n.bounds,opacity:n.opacity,rotation:Math.atan2(n.matrix[1],n.matrix[0])*180/Math.PI,parentId:n.parentId,contentVersion:n.contentVersion??n.id,d1Category:n.d1Category??'mg',localGeometry:n.localGeometry??{...n.geometry},...(n.process?{process:n.process}:{}),...(n.replacement?{replacement:n.replacement}:{}),...(n.hotspot?{hotspot:{x:n.hotspot[0],y:n.hotspot[1]}}:{}),observation:{state,reason,visibleBounds,basis:'production-recorded-geometry',paintedAreaPx2:state==='visible'?guaranteed.reduce((a,p)=>a+area(p),0):null},layer:n.z};
119
+ });
120
+ const defs=[],groups=ordered.map(n=>{
121
+ let body=n.body;if(n.type!=='raw'){const attrs=Object.entries(n.style).map(([k,v])=>`${k.replace(/[A-Z]/g,c=>'-'+c.toLowerCase())}="${esc(v)}"`).join(' ');body=n.type==='rect'?`<rect x="${n.x??0}" y="${n.y??0}" width="${n.width??0}" height="${n.height??0}" ${attrs}/>`:`<polygon points="${n.local.map(p=>p.join(',')).join(' ')}" ${attrs}/>`;}
122
+ let group=`<g data-object="${esc(n.id)}" transform="matrix(${n.matrix.join(' ')})" opacity="${n.opacity}">${body}</g>`;
123
+ n.clips.forEach((c,k)=>{const id=`obs-${n.index}-clip-${k}`;defs.push(`<clipPath id="${id}" clipPathUnits="userSpaceOnUse"><rect x="${c.local.x}" y="${c.local.y}" width="${c.local.width}" height="${c.local.height}" transform="matrix(${c.matrix.join(' ')})"/></clipPath>`);group=`<g clip-path="url(#${id})">${group}</g>`;});return group;
124
+ });
125
+ for(const o of objects){
126
+ const proof=Object.freeze({...o.observation,visibleBounds:o.observation.visibleBounds?Object.freeze({...o.observation.visibleBounds}):null});
127
+ o.observation=proof;recordedObservations.set(proof,{key:geometryKey(o),viewport:{width,height},observation:proof});
128
+ }
129
+ const frame={svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><defs>${defs.join('')}</defs>${groups.join('')}</svg>`,objects,...(cam?{camera:cam}:{}),renderedObjectIds:nodes.map(n=>n.id),observationBasis:'production-recorder'};
130
+ recordedFrames.set(frame,{svg:frame.svg,ids:JSON.stringify(frame.renderedObjectIds),objects:objects.map(o=>({observation:o.observation,key:geometryKey(o)})),viewport:{width,height}});
131
+ return frame;
132
+ }
133
+ return{rect:(s,style={})=>add('rect',s,style),polygon:(s,style={})=>add('polygon',s,style),raw:(s,body)=>add('raw',s,body),finish};
134
+ }
135
+ // Coverage checks compare the actual sampled state with the production timeline.
136
+ // They locate unrepresented changes and related actions; they do not invent causality.
137
+ function inspectActionCoverage(spec,samples,cutFrames=new Set()){
138
+ const actions=spec.actions??[],relays=spec.relays??[],ids=spec.coverage?.objectIds??[],eps=1e-5;
139
+ const rows=samples.filter(s=>(s.time??s.t)<spec.duration).map(s=>({time:s.time??s.t,map:s.map??new Map(s.frame.objects.map(o=>[o.id,o]))}));
140
+ const changed=(a,b)=>Number.isFinite(a)&&Number.isFinite(b)&&Math.abs(a-b)>eps;
141
+ const changes=[],uncoveredChanges=[],activeActions=new Set(),unresolvedPartIds=new Set();
142
+ for(const id of ids){
143
+ for(let i=1;i<rows.length;i++){
144
+ if(cutFrames.has(Math.round(rows[i].time*spec.fps)))continue;
145
+ const a=rows[i-1].map.get(id),b=rows[i].map.get(id);if(!a||!b||(a.opacity<=0&&b.opacity<=0))continue;
146
+ if(['subtitle-cue','source-footage'].includes(a.d1Category)&&a.d1Category===b.d1Category)continue;
147
+ const local=a.localGeometry&&b.localGeometry,part=!!(a.parentId||b.parentId),fields=[];
148
+ // Part-local values exclude inherited container/camera transport. Without them
149
+ // moving parts are unresolved, not automatically treated as internal action.
150
+ if(local){for(const k of ['x','y','width','height','rotation'])if(changed(a.localGeometry[k]??0,b.localGeometry[k]??0))fields.push('local.'+k);}
151
+ else if(!part){for(const k of ['x','y','width','height','rotation'])if(changed(a[k]??0,b[k]??0))fields.push('screen.'+k);}
152
+ else if(['x','y','width','height','rotation'].some(k=>changed(a[k]??0,b[k]??0)))unresolvedPartIds.add(id);
153
+ for(const k of ['maskProgress','pathProgress','morphProgress','occlusionProgress'])if(changed(a.process?.[k],b.process?.[k]))fields.push('process.'+k);
154
+ if(changed(a.opacity,b.opacity))fields.push('opacity');
155
+ if(!fields.length)continue;
156
+ const start=rows[i-1].time,end=rows[i].time,matching=actions.filter(x=>x.objectId===id&&x.start<=end+eps&&x.end>=start-eps);
157
+ matching.forEach(x=>activeActions.add(x.id));
158
+ const previous=changes.at(-1),covered=matching.map(x=>x.id).sort(),key=JSON.stringify([id,covered,fields]);
159
+ if(previous?.key===key&&Math.abs(previous.end-start)<eps)previous.end=end;
160
+ else changes.push({key,objectId:id,start,end,fields,actionIds:covered,visibility:visibleState(a,spec.viewport).state==='visible'&&visibleState(b,spec.viewport).state==='visible'?'confirmed':'unresolved'});
161
+ }
162
+ }
163
+ for(const c of changes)if(!c.actionIds.length){const {key,...rest}=c;uncoveredChanges.push(rest);}
164
+ const crossRelays=relays.filter(r=>{const a=actions.find(a=>a.id===r.fromAction),b=actions.find(a=>a.id===r.toAction);return a&&b&&a.objectId!==b.objectId;});
165
+ const measuredRelayIds=crossRelays.filter(r=>['follow','rigid-feedback'].includes(r.motionGate)).map(r=>r.id);
166
+ const uncoveredRelayIds=crossRelays.filter(r=>!measuredRelayIds.includes(r.id)).map(r=>r.id);
167
+ const relatedActionCandidates=[];
168
+ for(const child of actions.filter(a=>activeActions.has(a.id))){
169
+ const parents=new Set(rows.map(s=>s.map.get(child.objectId)?.parentId).filter(Boolean));
170
+ for(const parent of actions.filter(a=>activeActions.has(a.id)&&parents.has(a.objectId)&&a.start<=child.end&&a.end>=child.start)){
171
+ if(relays.some(r=>(r.fromAction===parent.id&&r.toAction===child.id)||(r.fromAction===child.id&&r.toAction===parent.id)))continue;
172
+ relatedActionCandidates.push({parentAction:parent.id,partAction:child.id,parentId:parent.objectId,partId:child.objectId,reason:'overlapping actual parent/part changes without a declared relationship; review whether causal or independent'});
173
+ }
174
+ }
175
+ const uncoveredActionIds=actions.filter(a=>!activeActions.has(a.id)).map(a=>a.id);
176
+ return{status:uncoveredChanges.length||uncoveredRelayIds.length||relatedActionCandidates.length?'incomplete':'represented-sampled-changes',basis:'sampled object/local-process changes matched to production event ranges; causality and script semantics remain unassessed',changes:changes.map(({key,...c})=>c),uncoveredChanges,actionsWithoutSampledChange:uncoveredActionIds,unresolvedPartIds:[...unresolvedPartIds],follow:{declaredCrossObjectRelayIds:crossRelays.map(r=>r.id),measuredRelayIds,uncoveredRelayIds,relatedActionCandidates,semantics:'not-assessed'}};
177
+ }
178
+ // These are source-frame coordinate observations, not speed-quality thresholds.
179
+ function measureFrameMotion(samples,ids,viewport,fps,actions=[],cutFrames=new Set()){
180
+ const objects=[],reviewFrames=new Map(),addFrame=(index,reason,id)=>{if(index<0||index>=samples.length)return;const frame=Math.round(samples[index].time*fps),item=reviewFrames.get(frame)??{frame,time:samples[index].time,objects:[],reasons:[]};if(!item.objects.includes(id))item.objects.push(id);if(!item.reasons.includes(reason))item.reasons.push(reason);reviewFrames.set(frame,item);};
181
+ for(const id of ids){
182
+ const rows=samples.map((s,sampleIndex)=>({sampleIndex,time:s.time,o:s.map?.get(id)??s.frame?.objects?.find(o=>o.id===id)})),steps=[];let path=0,unknown=0,visibleFrames=0,missingFrames=0;const events=[];
183
+ for(let i=0;i<rows.length;i++){const r=rows[i];if(!r.o){missingFrames++;for(const d of [-1,0,1])addFrame(r.sampleIndex+d,'missing-object-observation',id);continue;}
184
+ const v=visibleState(r.o,viewport);if(v.state==='visible')visibleFrames++;if(v.state==='unknown')unknown++;if(!i||!rows[i-1].o)continue;
185
+ if(cutFrames.has(Math.round(r.time*fps))){addFrame(i-1,'scene-cut-before',id);addFrame(i,'scene-cut-after',id);continue;}
186
+ if(r.o.notSubmitted||rows[i-1].o.notSubmitted){
187
+ if(r.o.notSubmitted!==rows[i-1].o.notSubmitted){addFrame(i-1,'draw-boundary',id);addFrame(i,'draw-boundary',id);}
188
+ continue;
189
+ }
190
+ const prev=rows[i-1],pv=visibleState(prev.o,viewport),a=prev.o.hotspot??{x:prev.o.x+prev.o.width/2,y:prev.o.y+prev.o.height/2},b=r.o.hotspot??{x:r.o.x+r.o.width/2,y:r.o.y+r.o.height/2};
191
+ const distance=Math.hypot(b.x-a.x,b.y-a.y),dt=r.time-prev.time;path+=distance;steps.push({frame:i,start:prev.time,end:r.time,distance,speed:dt>0?distance/dt:0,cumulative:path,confirmedVisible:pv.state==='visible'&&v.state==='visible'});
192
+ if(v.state!==pv.state||(prev.o.opacity>0)!==(r.o.opacity>0)){const e={frame:Math.round(r.time*fps),time:r.time,from:pv.state,to:v.state,drawSwitch:(prev.o.opacity>0)!==(r.o.opacity>0)};events.push(e);for(const d of [-1,0,1])addFrame(i+d,'visibility-boundary',id);}
193
+ }
194
+ if(!rows.some(r=>r.o))continue;const moving=steps.filter(s=>s.distance>EPS),peak=steps.length?steps.reduce((a,b)=>b.distance>a.distance?b:a):null,first=moving[0],last=moving.at(-1),span=first?last.end-first.start:0;
195
+ const cross=f=>{if(!path||missingFrames)return null;const s=steps.find(s=>s.cumulative>=path*f);return s?s.end-(first?.start??rows[0].time):null;};
196
+ const firstQuarterPath=first?steps.filter(s=>s.end<=first.start+span*.25+EPS).reduce((n,s)=>n+s.distance,0):0;
197
+ if(first){for(const f of [first.frame-1,first.frame,peak.frame-1,peak.frame,last.frame])addFrame(f,'motion-sample',id);}
198
+ objects.push({id,basis:rows.filter(r=>r.o).every(r=>r.o.hotspot)?'production-hotspot':'bbox-center-coordinate',fps,visibleFrames,unknownVisibilityFrames:unknown,missingFrames,coordinateCoverage:missingFrames?'incomplete':'complete',totalPathPx:path,pathViewportDiagonalFraction:path/Math.hypot(viewport.width,viewport.height),maxFrameDisplacementPx:peak?.distance??0,peakFrame:peak?Math.round(peak.end*fps):null,peakTime:peak?.end??null,peakSpeedPxPerSec:peak?.speed??0,visiblePathPx:steps.filter(s=>s.confirmedVisible).reduce((n,s)=>n+s.distance,0),motionDurationSec:missingFrames?null:span,t50Sec:cross(.5),t80Sec:cross(.8),firstQuarterPathFraction:missingFrames?null:path?firstQuarterPath/path:0,visibilityEvents:events,qualityAssessment:'not-assessed'});
199
+ }
200
+ const actionObservations=[];for(const action of actions){const selected=samples.filter(s=>s.time>=action.start-EPS&&s.time<=action.end+EPS),m=measureFrameMotion(selected,[action.objectId],viewport,fps,[],cutFrames);if(m.objects[0])actionObservations.push({...m.objects[0],id:action.id,objectId:action.objectId,start:action.start,end:action.end});for(const row of m.reviewFrames){const existing=reviewFrames.get(row.frame);if(existing){for(const reason of row.reasons)if(!existing.reasons.includes(reason))existing.reasons.push(reason);for(const id of row.objects)if(!existing.objects.includes(id))existing.objects.push(id);}else reviewFrames.set(row.frame,row);}}
201
+ return{basis:'actual production-frame samples; coordinates are retained for unknown visibility',qualityAssessment:'not-assessed',speedThreshold:null,objects,actions:actionObservations,reviewFrames:[...reviewFrames.values()].sort((a,b)=>a.frame-b.frame)};
202
+ }
203
+ return{createObservedScene,visibleState,recordedFrameState,measureFrameMotion,inspectActionCoverage,multiply,point};
204
+ });
@@ -0,0 +1,24 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {execFile} from 'node:child_process';
4
+ import {promisify} from 'node:util';
5
+ import {options,allowed,run} from './cli.mjs';
6
+ const execute=promisify(execFile);
7
+ async function probe(command,args) {
8
+ try {
9
+ const {stdout,stderr}=await execute(command,args,{timeout:10000,windowsHide:true,maxBuffer:65536});
10
+ return {available:true,version:(stdout||stderr).split(/\r?\n/)[0]};
11
+ } catch(e) {return {available:false,code:e.code || 'PROBE_FAILED'};}
12
+ }
13
+ await run(async()=>{
14
+ const o=options(process.argv.slice(2));allowed(o,['project']);
15
+ let exists=false;
16
+ try{exists=(await fs.stat(path.resolve(o.project))).isDirectory();}catch(e){if(e.code!=='ENOENT')throw e;}
17
+ const [ffmpeg,ffprobe,powershell]=await Promise.all([
18
+ probe('ffmpeg',['-version']),probe('ffprobe',['-version']),
19
+ probe(process.platform==='win32' && process.env.ProgramFiles ? path.join(process.env.ProgramFiles,'PowerShell','7','pwsh.exe') : 'pwsh',['-NoProfile','-Command','$PSVersionTable.PSVersion.ToString()'])
20
+ ]);
21
+ return {ok:true,readOnly:true,project:{path:path.resolve(o.project),exists},runtime:{node:{available:true,version:process.version},ffmpeg,ffprobe,powershell},
22
+ capabilities:{planning:'available',stateTools:'available',rendering:'unverified',actualListening:'unverified',hostSkillDiscovery:'unverified',tts:'external-only',imageGeneration:'user-manual-only',videoGeneration:'user-manual-only'},
23
+ note:'版本探测只证明命令可执行;未安装依赖,未登录、渲染或调用生成服务。实际视听与宿主加载须分别验证。'};
24
+ });
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ // MIT. Relation-level source locator and real-source sampler; no dependencies.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import crypto from 'node:crypto';
6
+ import {createRequire} from 'node:module';
7
+ import {fileURLToPath, pathToFileURL} from 'node:url';
8
+ const require=createRequire(import.meta.url);
9
+ const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
10
+ const sha=b=>crypto.createHash('sha256').update(b).digest('hex');
11
+ function inside(root, rel){
12
+ if(typeof rel!=='string'||path.isAbsolute(rel))throw Error('Index paths must be relative');
13
+ const p=fs.realpathSync(path.resolve(root,rel)),r=path.relative(fs.realpathSync(root),p);
14
+ if(r==='..'||r.startsWith('..'+path.sep)||path.isAbsolute(r))throw Error('Index path escapes package: '+rel);
15
+ return p;
16
+ }
17
+ export function locate({root=ROOT,relation,id,sample=false,full=false}={}){
18
+ if(!relation&&!id)throw Error('Provide relation or id; topic-level omission is not a match.');
19
+ const indexFile=inside(root,'assets/motion/process-index.json');
20
+ const index=JSON.parse(fs.readFileSync(indexFile,'utf8'));
21
+ if(index.schemaVersion!==1||!Array.isArray(index.processes))throw Error('Unsupported process index');
22
+ const terms=relation?.split(/[,,]/).map(s=>s.trim().toLowerCase()).filter(Boolean)||[];
23
+ const matchedTerms=terms.filter(t=>index.processes.some(p=>p.relations.some(r=>r.toLowerCase()===t)));
24
+ const unmatchedTerms=terms.filter(t=>!matchedTerms.includes(t));
25
+ const selected=index.processes.filter(p=>id?p.id===id:terms.some(t=>p.relations.some(r=>r.toLowerCase()===t)));
26
+ if(!selected.length)throw Error('No local causal relation matched; inspect available relations, not whole-topic similarity.');
27
+ return {schemaVersion:1,basis:'distributed-source-execution; not screen tracking or visual acceptance',index:{path:indexFile,sha256:sha(fs.readFileSync(indexFile))},query:{terms,matchedTerms,unmatchedTerms},detail:sample?'full-with-samples':full?'full':'concise',processes:selected.map(p=>{
28
+ const files=p.implementation.map(f=>{
29
+ const file=inside(root,f.path),bytes=fs.readFileSync(file),text=bytes.toString('utf8');
30
+ return {path:f.path,absolutePath:file,sha256:sha(bytes),anchors:f.anchors.map(a=>{const pos=text.indexOf(a);if(pos<0)throw Error(`Missing source anchor ${a} in ${f.path}`);return {text:a,line:text.slice(0,pos).split('\n').length};})};
31
+ });
32
+ const result=full||sample?{...p,matchedRelations:terms.filter(t=>p.relations.some(r=>r.toLowerCase()===t)),implementation:files}:
33
+ {id:p.id,matchedRelations:terms.filter(t=>p.relations.some(r=>r.toLowerCase()===t)),causalChain:p.causalChain,componentChain:p.componentChain,driverFields:p.driverFields,portableEntry:p.portableEntry,preserve:p.preserve,limits:p.limits,sourceSeconds:p.sourceSeconds,implementation:files.map(f=>({path:f.path,anchors:f.anchors})),next:'Use --id '+p.id+' --full for source hashes and reuse details; add --sample only when actual source states are needed.'};
34
+ if(p.portableEntry){
35
+ const entry=require(inside(root,p.portableEntry.path));
36
+ for(const name of ['stateAt','renderSvg','renderDocument'])if(typeof entry[name]!=='function')throw Error('Missing portable component export '+name+' in '+p.portableEntry.path);
37
+ }
38
+ if(sample){
39
+ if(p.sampler.unit!=='sourceSeconds')throw Error('Unsupported source timebase');
40
+ const mod=require(inside(root,p.sampler.path)),fn=mod[p.sampler.export];
41
+ if(typeof fn!=='function')throw Error('Missing executable source sampler '+p.sampler.export);
42
+ result.samples=p.sampleSeconds.map(sourceSeconds=>{
43
+ if(!Number.isFinite(sourceSeconds)||sourceSeconds<p.sourceSeconds[0]||sourceSeconds>=p.sourceSeconds[1])throw Error('Sample outside source range');
44
+ const state=fn(sourceSeconds);if(!state||typeof state!=='object')throw Error('Source returned no state');
45
+ return {sourceSeconds,state};
46
+ });
47
+ }
48
+ return result;
49
+ })};
50
+ }
51
+ async function main(){
52
+ const args=process.argv.slice(2);if(args.includes('--help')){console.log('node scripts/process-locate.mjs --relation 接收,处理 [--full] [--sample] [--out project/result.json]\nOr --id ep05-d06-receive-process-deliver. Exact relation aliases in assets/motion/process-index.json. Default output includes necessary component chains, driver fields, portable entries where available, source anchors and semantic limits. --full adds hashes and complete reuse details; --sample explicitly adds full source samples. The locator loads only bundled trusted portable entries to validate exports; --sample executes bundled state samplers. No install, rendering or visual pass.');return;}
53
+ const opts={};let out;
54
+ for(let i=0;i<args.length;i++){const k=args[i];if(k==='--sample')opts.sample=true;else if(k==='--full')opts.full=true;else if(['--relation','--id','--out'].includes(k)){const v=args[++i];if(!v||v.startsWith('--'))throw Error('Missing '+k);if(k==='--out')out=v;else opts[k.slice(2)]=v;}else throw Error('Unknown argument '+k);}
55
+ const text=JSON.stringify(locate(opts),null,2)+'\n';if(out)fs.writeFileSync(path.resolve(out),text,{encoding:'utf8',flag:'wx'});else process.stdout.write(text);
56
+ }
57
+ if(process.argv[1]&&import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href)main().catch(e=>{console.error(e.message);process.exitCode=1;});
@@ -0,0 +1,143 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Existing-runtime adapter. It never installs dependencies or downloads a browser.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {createRequire} from 'node:module';
6
+ import {fileURLToPath, pathToFileURL} from 'node:url';
7
+ import {createHash} from 'node:crypto';
8
+
9
+ const here=path.dirname(fileURLToPath(import.meta.url));
10
+ const exampleEntry=path.resolve(here,'../assets/motion/whole-result-return/src/entry.jsx');
11
+ export const help=`Render an editable motion example using an existing local runtime.
12
+ Required: --runtime PATH_TO_NODE_MODULES --browser PATH_TO_CHROME --out NEW_DIRECTORY
13
+ Select: --entry FILE --composition ID | --example whole-result-return
14
+ Optional: --mode stills|video --scale NUMBER
15
+ --frames 0,96,228 (stills) | --frames 0-119 (video, inclusive)
16
+ --props JSON_FILE --public-dir DIRECTORY --concurrency INTEGER
17
+ Defaults: stills / scale 0.5 / concurrency 2. No process is selected implicitly.
18
+ Example-local frame selection is used only for the bundled entry. A custom entry
19
+ defaults to its first, middle and last frame. Video mode is explicitly requested.
20
+ All generated files, browser temporary files and logs go under the NEW_DIRECTORY.
21
+ Audio is disabled; mix the current adopted audio separately after visual timing.
22
+ No output is overwritten. A new run requires a new --out directory.`;
23
+
24
+ export function parseArgs(argv){
25
+ if(argv.includes('--help')||argv.includes('-h'))return {help:true};
26
+ const allowed=new Set(['runtime','browser','out','entry','composition','example','mode','scale','frames','props','public-dir','concurrency']);
27
+ const raw={};
28
+ for(let i=0;i<argv.length;i+=2){
29
+ const key=argv[i]?.replace(/^--/,'');
30
+ if(!argv[i]?.startsWith('--')||!allowed.has(key))throw new Error('Unknown option: '+argv[i]);
31
+ if(raw[key]!==undefined)throw new Error('Duplicate option: --'+key);
32
+ const value=argv[i+1];
33
+ if(value===undefined||value.startsWith('--'))throw new Error('Missing value: --'+key);
34
+ raw[key]=value;
35
+ }
36
+ for(const key of ['runtime','browser','out'])if(!raw[key])throw new Error('Required: --'+key);
37
+ const mode=raw.mode??'stills',scale=Number(raw.scale??.5),concurrency=Number(raw.concurrency??2);
38
+ if(!['stills','video'].includes(mode))throw new Error('--mode must be stills or video');
39
+ if(!Number.isFinite(scale)||scale<=0||scale>4)throw new Error('--scale must be > 0 and <= 4');
40
+ if(!Number.isInteger(concurrency)||concurrency<1||concurrency>32)throw new Error('--concurrency must be an integer from 1 to 32');
41
+ if(raw.entry&&!raw.composition)throw new Error('A custom --entry requires its --composition ID');
42
+ if(raw.example&&(raw.entry||raw.composition))throw new Error('--example cannot be combined with --entry or --composition');
43
+ if(raw.example&&raw.example!=='whole-result-return')throw new Error('Unknown --example; use an explicit --entry and --composition');
44
+ if(!raw.example&&!raw.entry)throw new Error('Select --entry with --composition, or explicit --example whole-result-return');
45
+ return {...raw,mode,scale,concurrency,entry:path.resolve(raw.entry??exampleEntry),composition:raw.composition??'WholeResultReturn',
46
+ runtime:path.resolve(raw.runtime),browser:path.resolve(raw.browser),out:path.resolve(raw.out),
47
+ ...(raw.props?{props:path.resolve(raw.props)}:{}),...(raw['public-dir']?{publicDir:path.resolve(raw['public-dir'])}:{})};
48
+ }
49
+
50
+ export function selectFrames(spec,mode,durationInFrames,bundledExample=false){
51
+ if(!Number.isInteger(durationInFrames)||durationInFrames<1)throw new Error('Invalid composition duration');
52
+ const valid=f=>Number.isInteger(f)&&f>=0&&f<durationInFrames;
53
+ if(mode==='video'){
54
+ if(!spec)return [0,durationInFrames-1];
55
+ const match=/^(\d+)-(\d+)$/.exec(spec);
56
+ if(!match)throw new Error('Video --frames requires inclusive START-END');
57
+ const range=match.slice(1).map(Number);
58
+ if(!range.every(valid)||range[0]>range[1])throw new Error('Video frame range is outside the composition');
59
+ return range;
60
+ }
61
+ let frames=spec?spec.split(',').map(v=>/^\d+$/.test(v)?Number(v):NaN):
62
+ bundledExample?[0,96,159,228,366,432,550,660]:[0,Math.floor((durationInFrames-1)/2),durationInFrames-1];
63
+ if(!spec)frames=[...new Set(frames)];
64
+ if(!frames.length||!frames.every(valid))throw new Error('Still --frames must be comma-separated frame numbers inside the composition');
65
+ if(new Set(frames).size!==frames.length)throw new Error('Still frame list contains duplicates');
66
+ return frames;
67
+ }
68
+
69
+ function checkPath(target,kind,label){
70
+ const stat=fs.statSync(target,{throwIfNoEntry:false});
71
+ if(!stat||(kind==='file'?!stat.isFile():!stat.isDirectory()))throw new Error(label+' is not an existing '+kind+': '+target);
72
+ }
73
+ const hash=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
74
+
75
+ export async function render(options){
76
+ checkPath(options.runtime,'directory','Runtime');checkPath(options.browser,'file','Browser');checkPath(options.entry,'file','Entry');
77
+ if(options.publicDir)checkPath(options.publicDir,'directory','Public assets');
78
+ if(options.props)checkPath(options.props,'file','Input props');
79
+ if(fs.existsSync(options.out))throw new Error('Output directory already exists; choose a new --out: '+options.out);
80
+ for(const pkg of ['@remotion/bundler','@remotion/renderer','react','react-dom','remotion'])checkPath(path.join(options.runtime,pkg),'directory',pkg);
81
+ const inputProps=options.props?JSON.parse(fs.readFileSync(options.props,'utf8').replace(/^\uFEFF/,'')):{};
82
+ if(!inputProps||typeof inputProps!=='object'||Array.isArray(inputProps))throw new Error('--props must contain a JSON object');
83
+ const rootPath=path.resolve(here,'..');
84
+ const within=(parent,child)=>{const rel=path.relative(parent,child);return rel===''||(!rel.startsWith('..'+path.sep)&&rel!=='..'&&!path.isAbsolute(rel));};
85
+ if(within(rootPath,options.out))throw new Error('--out must be outside the Skill source directory');
86
+ if(within(options.runtime,options.out))throw new Error('--out must be outside the existing runtime');
87
+ fs.mkdirSync(path.dirname(options.out),{recursive:true});
88
+ fs.mkdirSync(options.out); // Atomic reservation: another run cannot reuse the same output directory.
89
+ const temp=path.join(options.out,'temp'),framesDir=path.join(options.out,'frames'),publicDir=options.publicDir??path.join(options.out,'public');
90
+ for(const dir of [temp,framesDir,...(options.publicDir?[]:[publicDir])])fs.mkdirSync(dir,{recursive:true});
91
+ // Remotion/Chromium see the process-local temp location before they are imported.
92
+ const previous=Object.fromEntries(['TEMP','TMP','TMPDIR'].map(k=>[k,process.env[k]]));
93
+ for(const key of Object.keys(previous))process.env[key]=temp;
94
+ const logPath=path.join(options.out,'render.jsonl');
95
+ const log=(type,data={})=>{const line=JSON.stringify({time:new Date().toISOString(),type,...data});fs.appendFileSync(logPath,line+'\n');console.log(line);};
96
+ let browser,phase='initializing',restoreSignals;
97
+ const beat=setInterval(()=>log('heartbeat',{phase}),30000);
98
+ const artifacts=[];
99
+ try{
100
+ log('start',{entry:options.entry,composition:options.composition,mode:options.mode,scale:options.scale,entrySha256:hash(options.entry),runtime:options.runtime,browser:options.browser});
101
+ const req=createRequire(import.meta.url);
102
+ const {bundle}=req(path.join(options.runtime,'@remotion/bundler'));
103
+ const {openBrowser,selectComposition,renderStill,renderMedia}=req(path.join(options.runtime,'@remotion/renderer'));
104
+ let cancelled=false;
105
+ const onSignal=()=>{cancelled=true;log('interrupted',{phase});process.exitCode=130;};
106
+ process.on('SIGINT',onSignal);process.on('SIGTERM',onSignal);
107
+ restoreSignals=()=>{process.off('SIGINT',onSignal);process.off('SIGTERM',onSignal);};
108
+ const assertActive=()=>{if(cancelled)throw new Error('Render interrupted');};
109
+ phase='bundling';
110
+ const serveUrl=await bundle({entryPoint:options.entry,outDir:path.join(options.out,'bundle'),rootDir:path.dirname(options.entry),publicDir,enableCaching:false,gitSource:null,
111
+ webpackOverride:cfg=>({...cfg,cache:false,resolve:{...cfg.resolve,modules:[options.runtime,'node_modules'],alias:{...cfg.resolve?.alias,react:path.join(options.runtime,'react'),'react-dom':path.join(options.runtime,'react-dom'),remotion:path.join(options.runtime,'remotion')}}})});
112
+ assertActive();phase='opening existing browser';browser=await openBrowser('chrome',{browserExecutable:options.browser});
113
+ const common={serveUrl,browserExecutable:options.browser,puppeteerInstance:browser,inputProps,timeoutInMilliseconds:120000};
114
+ const composition=await selectComposition({...common,id:options.composition});
115
+ const selection=selectFrames(options.frames,options.mode,composition.durationInFrames,path.resolve(options.entry)===exampleEntry);
116
+ log('composition',{id:composition.id,width:composition.width,height:composition.height,fps:composition.fps,durationInFrames:composition.durationInFrames,selection});
117
+ if(options.mode==='stills'){
118
+ for(const frame of selection){
119
+ assertActive();phase='still '+frame;const output=path.join(framesDir,'F'+String(frame).padStart(5,'0')+'.png');
120
+ await renderStill({...common,composition,frame,output,imageFormat:'png',scale:options.scale,overwrite:false});
121
+ artifacts.push({file:path.relative(options.out,output),frame,bytes:fs.statSync(output).size,sha256:hash(output)});log('still',artifacts.at(-1));
122
+ }
123
+ }else{
124
+ assertActive();phase='video rendering';let prior=-1;const output=path.join(options.out,'motion.mp4');
125
+ await renderMedia({...common,composition,outputLocation:output,codec:'h264',crf:16,pixelFormat:'yuv420p',muted:true,concurrency:options.concurrency,scale:options.scale,frameRange:selection,overwrite:false,
126
+ onProgress:p=>{phase=`rendered ${p.renderedFrames}, encoded ${p.encodedFrames}`;assertActive();const step=Math.floor(p.progress*20);if(step>prior){prior=step;log('progress',{percent:step*5,rendered:p.renderedFrames,encoded:p.encodedFrames});}}});
127
+ artifacts.push({file:'motion.mp4',bytes:fs.statSync(output).size,sha256:hash(output)});log('video',artifacts.at(-1));
128
+ }
129
+ const manifest={composition:{id:composition.id,width:composition.width,height:composition.height,fps:composition.fps,durationInFrames:composition.durationInFrames},scale:options.scale,selection,artifacts,
130
+ validation:'Technical rendering only. Not proof of semantic accuracy, motion quality, audio alignment or user acceptance.'};
131
+ fs.writeFileSync(path.join(options.out,'render-manifest.json'),JSON.stringify(manifest,null,2)+'\n');log('end',{artifacts:artifacts.length});return manifest;
132
+ }catch(error){log('error',{message:error.message});throw error;}
133
+ finally{
134
+ clearInterval(beat);restoreSignals?.();
135
+ try{if(browser)await browser.close({silent:true});}
136
+ finally{for(const [key,value] of Object.entries(previous)){if(value===undefined)delete process.env[key];else process.env[key]=value;}}
137
+ }
138
+ }
139
+
140
+ if(process.argv[1]&&import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href){
141
+ try{const options=parseArgs(process.argv.slice(2));if(options.help)console.log(help);else await render(options);}
142
+ catch(error){console.error(error.message);process.exitCode=process.exitCode||1;}
143
+ }