# Semantic Timelapse Formation **MKCV · beta, learning through use.** Mini Kernel Code Video is an evolving method. The examples explain how to work; observations of the film and corrections improve production and the knowledge for the next assignment. ## Adapt the method to your context A workshop explains a procedure, a museum tells a transformation, an author forms an invented scene. Preserve the relationship between subject, material, medium and the change understood by the audience. Sources, style, duration and tools change; the method starts from what the project has and needs to make possible. Give your AI the subject, audience, material and requested result. Let it guide production through the pertinent medium and observe what it produces. Preserve identity and camera when reconstructing from a reference; preserve source relationships in editing. MKCV remains beta: work and corrections evolve the method. **Choose the medium that fits the subject and material, then observe and improve the result.** ## A museum has images, footage and a story to tell A museum prepares a short explanation for visitors. It may have three illustrations, existing footage or an object that needs reconstruction and animation. These materials call for different work. First understand what the audience needs to see; choose how to produce it from there. Animatics, editing and editable scenes are composable possibilities, each with its own material and tools. ## Choose a path from the material and intent Understand what should become perceptible and what material exists. A new scene needs editable assets; an animatic organizes images through time; an edit works with existing clips. One work may compose several media. AI handles ordinary technical choices with the available tools and identifies material or a capability still needed. Preserve intent, current material and the requested result while writing, direction, performance and montage call on one another where they change the film. Produce a concrete version, observe it and correct what changes its meaning. A render or editing executor performs operations; understanding the film remains in the work of AI and the participating competences. Work beyond the turn requires an actually configured process. MKCV encompasses several production paths. This text deepens the reference-to-scene profile: work with existing images or clips starts from that material, as described in the operating guide. ## Understand the object Enter through the person's intent, the real subject, and the knowledge that makes its representation meaningful. Distinguish observed facts, source-bound interpretation, intended future and illustration. The subject determines the temporal transformation, not an inherited visual style. A film that depicts growing connections does not in itself show real AI learning. ## Image A — actual image-generator reference Form the image-generation instructions from relevant sources: recognisable subject, relationships, composition, future temporal needs, texts and limits of the representation. Use an **actual image generator** to make a first example image, and look at its visible result. The point is to avoid writing the visual first frame "from memory", not to reduce video RAM. If the example invents unsupported hierarchy, causation or structure, reform the instructions and the understanding of the object. If no image generator is accessible, acknowledge that A is not yet made, or receive an actual generated image from the person. A code-rendered PNG does not count as A. ## Image B — coded first frame **After observing A**, construct an editable scene and render its first frame in code. Reproduce relevant visible geometry or use A as an asset when useful; preserve source-bound identities, spatial relations, labels and parameters that the animation will need. A flat image does not expose hidden layers, true 3D depth, motion paths or causal structure. Image A and image B have different origins and functions; rendering t=0 cannot retroactively replace image generation. ## Narrative infographics, visible actors and 2.5D/3D The source may call for a **person, object, tool, setting, gesture or material change**, not just a node-and-line diagram. The method can form a structural infographic, a scene with characters and objects, an illustrated 2.5D space or a genuinely 3D scene. These are **composable possibilities, not obligatory categories**, and more depth is not automatically more truthful or understandable. When relevant, let the source specify each visual actor's **role, observable state, recognisable features, action and relation to others**. Form image A with these material distinctions and observe whether it invents a character's identity, authority, capability or causation. The animation should preserve the referent while camera, gesture, object state and text change. A representational character is not proof of a real human or autonomous agent. After A, construct B as an editable scene with actual assets and geometry. A flattened illustration does not automatically provide movable body parts, unseen surfaces, a 3D mesh, rig or depth. 2.5D can use layers, masks and parallax; genuine 3D needs models, cameras, materials and real execution tools. Select the medium through the change the subject needs to make visible. ## Time and the short film Use a time-explicit renderer, e.g. frame(t, scene). A 30-second film at 24 fps samples 720 times. Decide what changes and what remains recognisable. Observe B and meaningful moments through the sequence, including the ending. Motion, camera and labels can invent implications: a center may imply authority, a loop recurrence, and succession causality. Correct them against the actual source. Producing and encoding frames one at a time can limit **computer-memory use**. This is a separate technical issue from why A was requested. ## Let the source determine topology and the meaning of time The kind of relationship described by the sources should be able to change scene geometry. Two independent corrections may call for parallel paths rather than a luminous center. That arrangement serves that relationship; another subject may need a different form. Extend the renderer or explicitly preserve a difference it cannot represent. Separate **time in the source** from **time in the animation**. A 30-second explanatory motion may represent a process or comparison without compressing any real recorded timeline. Call it a documentary timelapse only when underlying events and intervals are actually available and used; otherwise describe the artifact as an explanatory temporal animation. Keep that distinction in image prompts, first-frame construction and the final film. ## Learning and recursion The generated image may reveal a missing relationship; the coded frame may expose an inaccurate translation; later frames may lose readability or identity. Use those observations to correct interpretation, image instructions, code or temporal method. Preserve reusable knowledge in the relevant competence: content, writing, visual design or technical production. If the knowledge already existed, make it reachable where it is needed. Keep possibilities supported by intent and sources open and correct substitutions introduced by interpretation. Record the learned relationship in the method that needs it. Persistence depends on the receiving environment; text and video do not by themselves modify model weights or start actions. ## VC-30s: an operating mini-kernel, not a required technology stack A short film can need source comprehension, image A generation, editable B, visual actors and objects, 2.5D/3D motion, sound, rendering and learning. These are complementary capabilities bound by one video object, **not eight mandatory phases or eight installed tools**. The [VC-30s operating competence field](VC30_OPERATIONAL_KERNEL.md) makes the relation portable; its public edition contains source links and technical distinctions with source links and portable technical knowledge. The transferable difference from studying HyperFrames, GSAP/Three.js, PixiJS, Motion Video, iart motion skills, Remotion and Framer Motion is not a chosen framework. It is the ability to **compose a scene at arbitrary time**, preserve character/object identity and source status, wait for assets, arrange narration/audio when useful, inspect encoded frames and return method learning to the appropriate competence. `real-time update(dt)` is not automatically a seekable `render(t)`. A generated image A remains distinct from scene B; a shader, rig or library is a technical means, not authority over what happened. A new recipient’s 3D or narrative production requires its own actual means and observed result. **From first visual reference to actually animable elements.** A is a real generated image to look at before coding B, but it is **not** a rig or the set of moveable parts. If the subject requires a hand, prop, character expression, separated foreground or true depth to move independently, recognise which additional consistent assets, poses, layers or geometry are needed; acquire them only when pertinent. Keep their source/provenance and identity, or instead change the motion/camera if A cannot support it. A single still may be entirely sufficient for a film that animates it as a whole. [VC-30s](VC30_OPERATIONAL_KERNEL.md) carries the deeper method, learned from a selective source audit rather than a claim to have read every project file. **Concepts and transfer between environments.** A short video may derive from an existing source-grounded concept that also produces infographics, articles or an interactive guide. Preserve the meaningful relation rather than copying visual layouts. Playback order alone cannot prove causation, hierarchy or irreversible progress. When A is generated in another receiver, the host coding B must actually reach its image bytes; a verbal description is not the observed reference. Screenshot-based cursor motion is illustrative unless the underlying action was observed. These are owner/routing capabilities, detailed in [VC-30s](VC30_OPERATIONAL_KERNEL.md), not new software requirements. **Image-first is not timeline-first.** In the VC-30s method, a genuinely generated and observed image A may be a key reference rather than the frame at `t=0`; the code-built scene B has its own initial state. When the subject describes actions, the actor, prop, camera and any caption or sound should express consistent aspects of the same source-grounded situation, without a mandatory state-machine architecture. A reusable template applies when the meaningful relationship persists; a different object may require a new visual grammar. See [VC-30s](VC30_OPERATIONAL_KERNEL.md). ## VC-30s Studio-Lab — specialized operating competences When the short film materially requires several disciplines, reach the [VC-30s Studio-Lab](VC30_STUDIO_LAB_EN.md). It brings **eleven conditional working stations** for source/meaning, art direction, image A generation/inspection, actors/assets, storyboard/time, code/2.5D/3D, text/voice, sound, render/inspection, delivery and learning. Each station can use specialist knowledge **during** a real production, with an explicit contribution and return to the responsible competence. They are not eleven steps every film must complete or an installed studio software suite. The image generator is a **real capability required for image A** in the selected image-first path; A is generated before coding B but may show a scene different from the film's opening `t=0`. Actors, objects, camera, captions and optional sound must represent a coherent source-bound situation. A reference file must genuinely reach whichever receiver codes B. The [Studio-Lab guide](VC30_STUDIO_LAB_EN.md) includes a minimal real-case record, material handoff and learning return; simply creating these instructions does not render a film. **MKCV, not just VC-30s.** The [Mini Kernel Code Video](VC30_STUDIO_LAB_EN.md#mkcv--mini-kernel-code-video-beyond-the-thirty-second-profile) is the general production capability. VC-30s remains one output profile; the eleven specialist Studio-Lab stations need not be duplicated for other duration or style. A real image generator, coded B, observed film and a non-identical later use must still be exercised in the reader's actual environment. **Animate the subject of image A.** When the request is to see the reference’s world move, form character, object, setting and camera movement inside that scene. Use actual layers, assets or an available image-to-video service. An overlaid diagram may explain a concept but produces a different effect. The [production guide](VC30_STUDIO_LAB_EN.md) develops this choice. **2.5D joints and subject identity.** For limited motion, separate relevant parts of the reference, construct masks and pivots and reconstruct revealed regions with their status clear. Observe whether the face, gesture and setting stay recognizable. Free camera motion or unseen surfaces may require actual 3D geometry. The [production guide](VC30_STUDIO_LAB_EN.md) distinguishes these means from a scene invented entirely in code. ## Actual means and effects An image generator, code execution and video encoder must actually be available to perform their respective steps. The receiving host may use Python/Pillow/FFmpeg, SVG/Canvas or another suitable medium. Source truth, asset rights, installation and public posting retain their own boundaries. Read OPERATING_GUIDE.md and EXAMPLES.md. The complete START_CHAT_EN.txt includes the operating knowledge for a chat without file access. ## MKCV — one film, reciprocal competences A film’s shared continuation preserves its subject, source status, current artifact and the question that can change it. Each specialist owns the knowledge and changes that belong to its work. A staging discovery may change the written scene; an edit may request another performance; an unavailable joint may change the intended gesture. Return the difference to that owner while keeping one recognizable film. [Read the reciprocal cinematic method](MKCV_CINEMA_EN.md). The four complementary public kits are linked from this resource’s page. ## Keep the film continuous when rendering stops When a render is long or interrupted, keep the intended timeline and render independently addressable frame intervals. Reuse a segment only after checking its inputs, code identity, frame count, dimensions, frame rate and decodability. A changed scene, asset or renderer calls for a new output identity. Segment boundaries are execution units; editing, gesture and narrative rhythm remain decisions about the film. A technical checkpoint preserves verified work. The project guide preserves subject, sources, reasons, open choices and what the next contributor must understand. Use both when needed: resuming an encoder does not restore an assistant’s understanding or start a background agent. Observing the resulting film may still change the scene, method or chosen medium. The kit also includes examples/recoverable_video: a local, bounded adapter, original scene, pinned job and verification script. Python 3.10+, Pillow, NumPy, OpenCV and local FFmpeg/ffprobe are required. Start with RECOVERABLE_VIDEO_EN.md. Conversations without these means use the production method and return an actionable continuation; instructions do not supply the tools. # Operating guide — choose the medium and form the film **MKCV · beta, learning through use.** Mini Kernel Code Video is an evolving method. The examples explain how to work; observations of the film and corrections improve production and the knowledge for the next assignment. ## Choose and guide production from the actual work Start with the subject, audience and existing material. AI recovers ongoing work, chooses an executable medium, composes the necessary competences and produces a version to observe. Ordinary technical choices continue within the assignment; missing material or a decision changing the work remains recognizable. The film may change medium when the result calls for it. **Scene from a reference.** When a new generated reference is needed, produce A with an actual image generator and observe it before coding. To animate its subject, form pertinent parts, layers or geometry: a bitmap does not automatically contain a rig. The following paragraphs deepen the construction of B in the reference-to-scene path. **Animatic from available images.** Order genuinely accessible images, assign durations and make the relationship between successive images readable. A camera move or caption can guide attention. An animatic shows rhythm and story; moving a view over a figure does not automatically animate its body. Existing material retains its origin. **Edit from existing clips.** Observe the footage, recognize what it documents and form order, duration and relationships with sound. Normalize format and encoding through actual tools, then observe the resulting file. A cut may make adjacent events appear causal: editing preserves relationships supported by sources. These paths are possibilities rather than three compulsory stages. A software demonstration starts from real capture; a three-dimensional scene needs models and a renderer; video generation needs an actually accessible provider. Connect the necessary medium or preserve the open difference without presenting it as an already produced video. ## Reconstruct a reference while preserving camera and identity When likeness to the reference matters, compare the scene through the same view. Understand framing, volumes, silhouettes and relationships between subjects first; deepen details, materials and atmosphere from there. Correcting a face or tree does not establish fidelity of the whole scene. A side view may reveal structure hidden by the frontal frame: three-dimensional reconstruction and composition for a single camera have different scopes. Keep an editable version and observe which parts materially change perception. The camera stays a shared reference while you correct the pertinent object. Comparing regions helps localize differences; pixel similarity alone does not decide identity, gesture or film meaning. ## Method, tools and execution have different roles The kit transfers the operating method, the existing-image renderer example and the bounded recoverable-video example. Editing tools, models, providers and assets belong to the project using it. AI forms and observes choices; a local executor applies operations to supplied material. A configuration described in a document does not itself start work after the conversation. ## Deepen the reference-to-scene path **Form the image instruction from knowledge.** Recover what the subject actually is, what relation the film may represent and what must remain recognisable. For the image-generator prompt include composition, relevant geometry, exact text, and when material the visual spaces later frames may occupy. A known motif is not a default. **Generate and inspect A.** Use a real image-generator tool first. Observe the actual output, not an imagined description. Correct invented hierarchies, implied time or false causal relations before committing the representation to code. Keep the image's provenance. **Translate to B.** Build editable scene code after seeing A. Choose whether to reconstruct visible structures, use the picture as an asset or combine methods. The bitmap does not reveal hidden layers, depth, paths or facts. Render the separate coded first frame t=0 and observe it. **Visual narrative from the source.** Do not begin from a predetermined glowing kernel, a mandatory diagram or a generic 3D look. When an event is made clearer by people or objects, form a minimal visual identity for each: source referent, role, appearance anchors, state, action and consequence. The image-generator prompt may include setting, gesture, props, material, perspective, light and empty space for later captions. A is an observed design reference, never a true record of unobserved events. **2.5D and genuine 3D.** Use A as a backdrop or texture, or construct actual layers, masks, sprites and parallax. Moving the camera across a flat image does not create a backside or character rig. Use 3D geometry where space changes understanding and you have the means to build it. Preserve the actor’s identity through transformations. Correct occlusion and continuity through visual design and technical production; correct meaning through the content’s sources. **Form the temporal change.** Use an explicit time parameter and stable object identities. A 30 s × 24 fps example has 720 samples. Let source data change text and geometry rather than hard-coding the first example as universal. Inspect later occlusion, text boundaries, the end state and unexpected implications of camera or montage. **Visual reference and encoding memory.** The generated image supplies an observable reference for constructing the scene. The RAM needed to export the video depends on the encoding process: sending one frame at a time to an encoder can limit its use. **Geometry follows the represented relationship.** Two independent observations may require distinguishable paths. The reusable knowledge is to let the kind and number of relationships change geometry and code. Extend the renderer or make an unrepresentable difference explicit rather than forcing it into the nearest available shape. **Two clocks.** The factual time of source events and the playback time of a 30-second video are not interchangeable. A narrated explanation of dated technical corrections is not automatically a timelapse of those actual events. Documentary time-lapse requires evidence of the underlying source intervals, while conceptual animations can have their own explicit display time. **Keep the method in your project.** When a correction changes how the film is built, preserve what changed, why and where later work will recover that knowledge. Update instructions and assets that actually depend on the correction. Use the guide or knowledge location already present in your environment. **Return learning.** Differences can change source comprehension, the generator instruction, the editing scene or the method. Preserve what occurred and what was understood then. Return reusable knowledge to the appropriate competence. If there was no image generator, do not mislabel render(t=0) as its output. **VC-30s competence composition.** For a film that involves several kinds of work, enter [VC30_OPERATIONAL_KERNEL.md](VC30_OPERATIONAL_KERNEL.md) before assuming the previous procedural renderer is the medium. Its methods bring sourced meaning, generated reference A, actor/object continuity, time-seekable animation and optional audio into the same film without a universal stack. HyperFrames and Remotion are alternative carriers; GSAP/Three/Pixi/Framer Motion examples often animate real-time UIs and need an explicit time model for deterministic video. Repository reading alone does not install them. Remotion's licensing differs from MIT/Apache. **Image A is not a set of independent moving parts.** After seeing A, recognise whether the action needs independently animated components or further poses/views/masks/geometry. Make only the necessary parts from source-consistent references; preserve their identity and provenance. If those parts cannot be constructed faithfully, change the camera or the expression. Do not turn a flat generated image into a claimed 3D rig. Decide which parts must remain editable across renderers before choosing a native, hosted or finished-video carrier. **Visual reference versus the film's first time.** Generate and inspect A first, but do not presume it is the `t=0` state. It may be the scene's signature pose or strongest relation. Before coding B, understand what identity A contributes and which scene state should actually start the film. When actions matter, build the actor, object, camera and cue descriptions from a consistent source relation rather than unrelated animation tracks. A different source may require a newly formed scene, not only a changed text prop. **Studio-Lab operating station routing.** When the production needs source interpretation, generated imagery, character assets, 3D or sound beyond one simple scene, use the [VC-30s Studio-Lab](VC30_STUDIO_LAB_EN.md) to reach the **smallest relevant set of specialist competences**. The work may return from coded B to image A or editorial meaning; no one-pass, eleven-stage pipeline is assumed. A case record distinguishes actual asset access, generated vs observed frames, rendered MP4 and any real delivery effect. **Technical carrier.** The public example code is not a full semantic timelapse engine. It can test an existing generated picture → coded frame → MP4 path, but camera movement alone does not represent the actual subject. # MKCV — one film, reciprocal competences A film’s shared continuation preserves its subject, source status, current artifact and the question that can change it. Each specialist owns the knowledge and changes that belong to its work. A staging discovery may change the written scene; an edit may request another performance; an unavailable joint may change the intended gesture. Return the difference to that owner while keeping one recognizable film. Cinematic Screenwriting forms world, situation, action and authored words. Cinematic Direction forms the perceptible encounter through staging, camera and light. Character & Object Performance forms readable action and reaction. Film Montage forms the relationship between images and sound. Code production constructs and observes the actual executable medium. These public kits are available separately in the same collection. They can compose through a shared project guide without a required orchestration API, framework, crew size or fixed order. A file handoff must actually reach the receiver that uses it. Asset rights, public delivery and external actions keep their own authority. When producing a film, keep the generated files, editable scene and observations needed to resume it. Available method, present tools, exported film and use in another project describe different results. ## Keep the film continuous when rendering stops When a render is long or interrupted, keep the intended timeline and render independently addressable frame intervals. Reuse a segment only after checking its inputs, code identity, frame count, dimensions, frame rate and decodability. A changed scene, asset or renderer calls for a new output identity. Segment boundaries are execution units; editing, gesture and narrative rhythm remain decisions about the film. A technical checkpoint preserves verified work. The project guide preserves subject, sources, reasons, open choices and what the next contributor must understand. Use both when needed: resuming an encoder does not restore an assistant’s understanding or start a background agent. Observing the resulting film may still change the scene, method or chosen medium. The kit also includes examples/recoverable_video: a local, bounded adapter, original scene, pinned job and verification script. Python 3.10+, Pillow, NumPy, OpenCV and local FFmpeg/ffprobe are required. Start with RECOVERABLE_VIDEO_EN.md. Conversations without these means use the production method and return an actionable continuation; instructions do not supply the tools. # Worked examples Illustrative cases for adaptation. ## Animate the world in the reference A generated illustration shows a robot beside a worktable. The entrusted film asks that world to move. Adding a new overlay of boxes would make a different film. Observe the actual reference, identify the relevant head, arm, prop and environment, then determine which layers, pivots or geometry are available. A restrained 2.5D articulation may preserve identity better than an invented full 3D body. If hidden surfaces matter, form them as an explicit reconstruction or choose another view. The method follows the actual intended motion. ## A museum explores rhythm with three illustrations A museum has three drawings of a tool and its use. Order, durations and points of attention suffice for an initial explanation: AI forms an animatic from the existing images, observes it and revises the timing of the discovery. If visitors need to understand how a lever moves, panning over the figure is insufficient: animatable parts or footage of the gesture become pertinent. The medium changes through what the audience needs to understand. ## A workshop edits a demonstration from existing footage A workshop has filmed preparation, assembly and operation of an object. AI observes the clips, connects the steps and edits an explanation from actual footage. A time jump stays recognizable; adjacent images do not invent a cause. The project supplies clips and an editing tool. Observing the finished video may call for another cut or a missing view, rather than a new generated reference. ## An interrupted illustrative scene resumes its own timeline A project has an original coded orbital scene and a fixed 72-frame timeline. After one 12-frame segment, production stops. The same job resumes: it decodes the completed segment, checks its identity and renders the remaining intervals. A changed job is kept separate; a damaged segment is quarantined and rebuilt. The completed local file is checked as a whole. This example teaches technical continuation; the scene’s orbit is illustrative and its on-screen labels are the original Italian artwork, not scientific observation or a customer result. # VC-30s — Operational competence field for code-made short videos MKCV encompasses several production paths. This text deepens the reference-to-scene profile: work with existing images or clips starts from that material, as described in the operating guide. MKCV is beta and learning. Work on the film and the resulting observations evolve the method. This method connects subject understanding, visual design, code, sound and learning to produce a film. Public edition 0.1.4 supplies the knowledge; the receiving environment supplies image generation, tools and export capabilities. **MKCV — Mini Kernel Code Video** names the general composition of production competences. **VC-30s** is the short-duration profile described here. Both use the [same production guide](VC30_STUDIO_LAB_EN.md); duration and format follow the requested film. ## Form the film from the actual subject The subject, its source, what is observed vs illustrated, the receiving viewer and the meaningful change determine which capabilities should participate. The mini-kernel can combine source understanding, generated visual references, storyboard/design, 2D/2.5D/3D scene implementation, timeline composition, optional narration/sound, encoding/inspection and return of reusable learning. Not every video needs characters, Three.js, voiceover or an independent image sequence. **Image A** is a real output from an image generator, generated from source-bound instructions and **observed before writing the first visual frame in code**. The purpose is to avoid relying only on the model's visual recollection. **Image B** is the coded first frame of an editable scene, not a substitute for A. A bitmap does not provide hidden depth, character rigging or real events; the executable scene must acquire these if the film requires them. An actor or object needs a recognisable identity across time: referent, role, visual features, observable state, actions, relations and, if necessary, pose, prop contacts and camera visibility. Isometric SVG/CSS or layered 2.5D can communicate depth; true 3D requires actual geometry, lighting and camera when they materially help understanding. ## Composing possible technical carriers **HTML/video:** [HyperFrames](https://github.com/heygen-com/hyperframes) uses timed HTML clips and seekable timelines, with GSAP and custom `hf-seek` rendering for Canvas/Three.js. Its framework is Apache-2.0. **React/video:** [Remotion](https://github.com/remotion-dev/remotion) uses `useCurrentFrame()`, compositions and sequences. Its Remotion License is **not** an unrestricted MIT or Apache license: consult current free/company terms for the user's organization. **2D/interaction:** [PixiJS/GSAP example](https://github.com/AhmadDinkaa/pixijs-tic-tac-toe) separates scene objects, game state, feedback animations and sound. For a film, convert real-time event callbacks to frame-addressable states. **Web/3D:** [GSAP/Three.js example](https://github.com/TheWebxite/phans-custom-tailor) provides shader-based fabric/photo effects and fallbacks, but a WebGL realtime loop cannot be assumed seekable. The source's license for code/asset reuse must be resolved separately. **Narration/audio:** [Motion Video](https://github.com/bestagentkits/motion-video-skill) offers beat-aligned speech/captions/music and a measured export loop; its provider credentials and specific thresholds do not become universal requirements. **Motion craft:** [iart motion-skills](https://github.com/iart-ai/motion-skills) links targeted skills for storytelling, character drawing, isometric projection, data infographics, WebGL, audio and frame inspection. Acquire only the relevant competence and treat each pack's examples separately from its general craft. **Web motion language:** [modern-portfolio](https://github.com/sanidhyy/modern-portfolio) uses Framer Motion variants and layered page transitions; learn the coordination, not the website's styles or automatic video support. These sources are **mechanisms and learning resources**, not installed providers. No code, images, fonts, music or shader assets are copied into this public skill. Resolve dependencies and permissions in the actual receiving environment. ## Learning from other people's methods, without copying their implementation The following technical sources teach choices about scenes, assets and time. Select tools through the actual work and preserve the conditions of reused capabilities. **From labels to a perceptible medium.** A word like “cinematic” or “modern” cannot specify the scene. Let the actual subject make material, shape, framing, lighting and behaviour meaningful in image-generator reference A. Observe A as a **visual hypothesis**: do not repeat its arbitrary composition or false causal hints in coded scene B. Named looks, lists of default bans, numerical timing rules and branded styles from the source projects are not rules for the receiving project. **From an illustrated character to a coherent action.** If a person or object matters to the film, recognise the visual features, pose, gaze, contact points and relations that must continue. A hand holding a tool, an eye directed at the object and a prop crossing a camera cut express a persistent relation, not just animated pixels. A flattened A cannot reveal the unseen back, a rig or hidden object geometry. Use a different viewpoint or an appropriate real asset rather than inventing those parts. **From movement to a first-time reading.** A scene can be understood through what the eye can follow: action, consequence, hold, change of framing, words and silence. Time can illustrate sequence, comparison, uncertainty or cause; do not force every adjacent shot into a causal chain. If voice or music matters, use meaningful action/word cues rather than arbitrary timestamps, while allowing silent videos when appropriate. **From render inspection to learning.** A still can expose geometry, a moving clip pacing, an encoded frame an export issue. These observations can refine the nearest method without creating an approval ritual. A model's assessment “as a first-time viewer” is not evidence of actual audience comprehension. Preserve that distinction. The learned faculty is **situated perceptual translation**: understanding a source, forming an observable visual reference, and deriving a reproducible temporal expression that keeps the subject's meaning. Code and runtime decisions remain with the technical owner; no source project's code, assets or styles are bundled here. ## Prepare animatable elements from the reference Before constructing motion, identify which image elements need to move separately and which can remain one asset. The first genuinely generated and inspected **image A remains the visual reference**. It may establish art direction, the relation between characters/objects and the readable whole. But a single flattened illustration cannot independently animate a hand, held tool, background, eye movement or the reverse view of an object. When the actual motion needs them, form **additional source-bound visual elements, poses, masks or geometry**; when a single whole image suffices, keep it whole. Additional assets should remain coherent with the subject and A, while their provenance and roles stay identifiable. They are not retroactively relabelled as the first A. This distinction was learned from [Generative Illustration](https://github.com/iart-ai/generative-illustration-skills), whose working methods separate illustrations into independently animable units. One of that project's source documents cautions that naïve SVG background removal can delete a foreground object. The lesson is to **preserve the subject when isolating parts**, not import a particular algorithm, template or vector file. [HyperFrames media-use](https://github.com/heygen-com/hyperframes) also teaches that reused assets require source identity and separation across projects. An asset belongs to its context; a vaguely similar cached logo or illustration does not acquire the right identity. For a new video receiver, preserve the provenance/role needed to use media correctly, without assuming HyperFrames' own file manifest. **What remains editable matters.** A scene translated into native editable elements, hosted time-seekable code or a finished rendered clip preserves different editing abilities. The rendered clip is not the same as a freely movable character. [Remotion ThreeCanvas](https://github.com/remotion-dev/remotion) is one example of 3D tied to absolute frame time, if that renderer is actually chosen. **Format and language belong before the render.** A 16:9 master often must be **recomposed**, not merely cropped, for 9:16 while preserving people, objects and titles. Exact words should remain editable and, where appropriate, accessible through captions or transcripts, not be guessed from pixels in A. Current social platform overlay dimensions need case-specific confirmation. Preserve the provenance and rights of the assets and code actually used in the project. ## Before and beyond the film: concept, non-linear relation, real asset transfer These relationships can change the representation before a renderer is chosen. **A media concept can precede the clip.** When an existing editorial or product concept already has a source-grounded core, a short video is one possible expression of that core alongside a still infographic, presentation or interactive guide. Recover the source, dominant relation, real-world consequence and audience before forming the image A prompt; do not derive the claim solely from a prior clip's visual treatment. Other derivatives preserve the thesis, not the same crop. A new A should still be actually generated and observed when this image-first workflow is selected. **Linear playback does not make the subject linear.** A video can show co-presence, alternative interpretations, contrast, a recursive return that changes future possibilities, or present capability beside an open future horizon. Do not silently turn adjacency of shots into cause and effect, or a loop into an identical return. The appropriate temporal grammar emerges from the **kind of relation**, not from the number of seconds. **Presentation and cognitive navigation are different capabilities.** A video may introduce a system through space, action and consequence, and share a visual identity with an interactive guide. The MP4 itself cannot accept selections, maintain live state or perform operations. Preserve that boundary when deriving other media from the same concept. **Receiving an image is not receiving its description.** If one host generates A and another builds code scene B, the coding host must be able to **access the original image bytes or a genuinely accessible asset**, and know what was observed in it. A prompt, screenshot shown only in another chat or link to an instruction file does not complete that handoff. Use the existing storage/attachment/connector channel when available; do not invent an always-on bridge or require a universal metadata schema. **Screenshot-based demos are not necessarily live product demonstrations.** An animated cursor can illustrate a possible flow, but does not establish that the UI click or automated result occurred in a running product. Distinguish captured screen, illustrative reconstruction and observed execution where the difference affects the claim. These are reusable **perceptual and capability distinctions**, not copied code or mandatory preproduction stages. ## Image A precedes the coding, not necessarily frame zero The first generated visual reference A is made and inspected **before programming the animation**, but it need not depict the video at `t=0`. It can be a key visual, a recognizable character, the most revealing action, a spatial relation or a representative moment. The coded scene B has its **own** opening state, and the useful relation to A may become visible later in the film. Do not force a pixel-identical first frame merely because A was generated first in the work. **One represented situation, many visible projections.** Where the subject contains actions or changes of state, actors, held objects, camera views, text and sound should represent **consistent aspects of the same source-bound situation**. A click, gesture or change of viewpoint is not automatically evidence that an event actually occurred. Some films can be rendered from a simple shared relationship; others may benefit from a more elaborate model of actors, events and scene states. No formal state machine is universally required. **A data variation is not always a different subject.** A reusable scene can render new values or variants when the underlying relationship remains appropriate. A truly different case may require a new perspective, visual grammar, source interpretation or initial image prompt rather than merely swapping names and colours in an old template. Preserve the *way of forming* scenes as reusable knowledge, not the scene geometry as a universal style. ## Studio-Lab: use knowledge at the working station The [Studio-Lab](VC30_STUDIO_LAB_EN.md) connects source knowledge, visual direction, image A, assets, storyboard, code, voice and sound, export and learning. Use the specializations relevant to the film with the actual means of your environment. ## A video must be addressable in time The export scene should support `frame(t, scene, assets)` or an equivalent absolute-frame method that can render frames **out of order**. GSAP tickers and Three.js `update(dt)` are live-web mechanisms, not an assurance of deterministic video. Seed randomness, wait for images/fonts/GPU to be ready, and preserve identities between shots. 30s × 24fps = 720 frames, but neither format nor frame rate is universal. Separate **source time** (real recorded events and intervals) from **presentation time** (the timeline of the explanatory animation). When only the latter exists, the output is an explanatory short rather than documented time-lapse footage. Audio and caption cues should share time data with the film if they contribute meaning. Silence can be the correct result. Check actual encoded duration, dimensions and track presence plus representative decoded frames when those claims matter; observing a clip is not proof of viewer understanding. ## Reusable recursive return An image may introduce a false hierarchy; a character may lose its identity while turning; an HTML animation may fail to seek; a caption or soundtrack may create a misleading temporal implication. Correct the source interpretation, image instruction, visual design, code, sound or receiver method **at the owner that must act differently next time**. If a method already existed but was not reached, improve discovery, not the number of skill files. No claim that an exported film changes model weights or self-installs tools. **Use in your environment:** exercise the method through real tools and assets. A new narrative subject or 3D scene needs observations of the film actually constructed. **Source coordinates and provenance:** this portable text distills methods from the linked projects as read on 24 October 2026. Source versions and licenses may change; re-open the actual repository where an integration/asset choice becomes material. # VC-30s Studio-Lab — building code-made video with specialized competences MKCV encompasses several production paths. This text deepens the reference-to-scene profile: work with existing images or clips starts from that material, as described in the operating guide. MKCV is beta and learning. Work on the film and the resulting observations evolve the method. **State:** public **edition 0.1.4** method. Usable as a working guide in a chat or harness that actually has image, file, coding and rendering capabilities. **Not** an installed video software suite, always-on agent or guarantee of third-party provider availability. The method builds on [Semantic Timelapse Formation](SKILL.md) and [VC-30s Operating Field](VC30_OPERATIONAL_KERNEL.md). ## MKCV — Mini Kernel Code Video, beyond the thirty-second profile **MKCV** names the composition of competences for producing coded films. **VC-30s** identifies a short-duration profile. The stations in this guide can contribute to films with different durations, formats and visual languages when their subject calls for them. **Public operating method:** use these instructions with the actual tools in your environment. Keep the generated and observed image A, editable scene B and exported film so the work can be resumed and improved. ## A production studio, not a software catalog A short film can require different faculties: source understanding, visual direction, generated reference, people and objects, spatial/temporal grammar, code, speech and audio, rendering, delivery and learning. **Each station contributes situated know-how** and returns its causal learning to the nearest semantic owner. These faculties can work in one assistant or across multiple receivers with actual file access. The document alone does not invoke them. Stations are **available when materially relevant**, not eleven mandatory phases in a fixed sequence. An image may be the right final result; voice may shape the storyboard before it is settled; viewing the generated image may change the source interpretation. ## Eleven competent production stations | Station / competence | Know-how used during production | Contribution to the shared case | | --- | --- | --- | | **Source and concept** — domain/editorial | Distinguishes observed facts, interpretation, illustration and future possibility; identifies the subject and audience | A source-grounded film nucleus | | **Art direction** — perceptual composition | Selects visual relations, material, light, frame, space and depth from meaning rather than presets | Direction for generated reference and readable hierarchy | | **Image A** — image-reference formation | Forms a source-bound prompt, generates a real image using an available generator, observes it | Accessible A asset, origin and what it teaches; A need not be film `t=0` | | **Actors and assets** — visual continuity | Discerns needed independently moving elements, poses, props, layers, masks and actual geometry | Consistent identity and genuinely available resources | | **Storyboard and time** — temporal direction | Distinguishes cause, co-presence, contrast, return and sequential change | Scene relation, beats/cues, world and camera continuity | | **Coded scene B and animation** — code medium | Builds an editable 2D/2.5D/3D scene that can be rendered at time T | The actual coded first frame B, time-addressable movement | | **Words and voice** — editorial expression | Holds exact claims/values and readable, editable captions, narration timing and accessibility | Spoken/on-screen text, or justified silence | | **Sound** — audio craft | Forms sound events, atmosphere and music when they matter; recognizes rights and timing | Cue/mix/tracks or an audio-free result | | **Render and inspect** — technical/perceptual readback | Exports through a real renderer and inspects frames and video files | Actually existing output and consequential corrections | | **Delivery and derivatives** — channel competence | Adapts formats, subtitle and editability; recomposes layouts when crops destroy meaning | Actual carrier for the selected receiver/destination | | **Learning and continuity** — meta competence | Distinguishes a completed artifact from knowledge that should change later work | Returned method, updated case and next point of reentry | ## Animate the reference’s subject Clarify the requested movement: animate the character and objects depicted in the reference, construct a model from that image or create a new scene from the same concept. The three requests may need different assets and methods. When the intended medium is image-to-motion, identify **a gesture within A** before drawing a new explanatory layer. technical production may use masks, 2.5D layers, coherent additional assets, restoration behind moving regions, an actual 3D model if needed, or image-to-video synthesis by a connected provider. A flattened A is not a hidden rig or a guarantee of temporal consistency. Diagrams and captions may help when they convey meaning, but must not replace the subject's movement. **Optional technical receiver, not a dependency:** [Motion.so MCP](https://docs.motion.so/guides/mcp) documents agent-driven creation/revision, media uploads and video outputs. It does not prove that a given source image will be animated faithfully. It needs account permissions/OAuth and may consume credits; a local file must be uploaded before Motion can read it. The Motion product advertises social connections, but the documented MCP video tool list does **not itself establish direct social-posting tools**. Publication authority remains with the channel owner. ## Preserve identity and geometry in 2.5D animation For limited movement, extract the head, arm or other relevant parts from the reference, define masks and pivots and reconstruct regions revealed by motion. Distinguish original pixels from reconstructed background. Light and camera should continue to describe the same setting. Distinguish three production modes: animate the same image with 2.5D layers; construct 3D geometry from the reference; create a new scene entirely in code. The first serves limited motion and views. Free rotation, new surfaces and occlusion need the relevant geometry. Choose through the subject and requested effect. The work drew **methods** from [cinetic](https://github.com/Leonxlnx/cinetic) (subject-owned movement and film direction), [img2threejs](https://github.com/img2threejs/img2threejs) (component inventory, hierarchy and unseen-part uncertainty), and [Remotion agent skills](https://github.com/remotion-dev/skills) (composition versus rendered outcome). Neither their implementation code, stylistic constraints nor templates were imported. Reconstructing eyelids or facial features can alter the character’s identity. Inspect the result and choose a smaller gesture when it preserves the subject better. Signs already present in the reference belong to the original scene; new panels or diagrams add another representational layer. For a different cinematic expression, form a new reference or coherent model. ## Operating from an actual case Reach the **current source** and the material question first; do not activate all stations because they are listed. For the image-first path, form instructions and **generate a real image A**, then inspect it. A can be a key visual, character, representative scene or important moment; being first **in the production process** does not mean showing frame zero **of the film**. When the action needs independent movable parts, acquire only the necessary additional assets coherent with A and the source, rather than imagining unseen body parts or 3D rigs. Let the **type of relation** determine temporal expression. Build coded scene B with its real opening state and a renderer that can address time T (or an equivalent frame index) independently from uncontrolled browser timing. A simulated cursor over screenshots is an illustrative walkthrough, not evidence of an observed product action. If image A and scene B are handled in different environments, the coding receiver must **actually access A's file bytes**. Merely providing a prompt, a text description or a skill link does not transfer the visual reference. Audio files, fonts and provider rights/credentials likewise require actual availability. Inspect the delivered output as an artifact: read file metadata for duration, codec and dimensions; see representative frames/real playback to understand motion and legibility. Internal inspection is not proof that a real audience has understood the film. ## Minimal production case record Create this **only after a case is selected**; retain just what changes continuation: - **Subject:** source/version, intended audience and factual status (observed, reconstructed, allegorical, possible). - **Active competences:** why each participated, real inputs/outputs and responsible owner. - **A:** prompt, generated reference file actually reachable, provenance, observations and limits. - **B:** editable scene, first coded frame, available assets, meaningful temporal model. - **Output:** real film/other carrier, measured technical details and any actual distribution state. - **Learning:** causal difference to apply in another case, owner whose future method changes, path/receipt and next state. This is a continuity method, not a mandatory form. Keep private/client media and secrets in authorized locations. ## Research sources and limits Know-how was studied from [HyperFrames](https://github.com/heygen-com/hyperframes), [Remotion](https://github.com/remotion-dev/remotion), [PixiJS/GSAP](https://github.com/AhmadDinkaa/pixijs-tic-tac-toe), [GSAP/Three.js](https://github.com/TheWebxite/phans-custom-tailor), [Motion Video](https://github.com/bestagentkits/motion-video-skill), [iart motion skills](https://github.com/iart-ai/motion-skills), and [modern-portfolio](https://github.com/sanidhyy/modern-portfolio). We transfer **knowledge and method**, not their source code, shaders, images, fonts or templates. This is selective research, not a claim to have read every repository file. Runtime and licensing must be resolved in the environment that actually uses them. **Stopping condition:** a case may conclude with a film, a better image, a corrected method or another medium altogether. Duration, format and number of stations are not axioms. # MKCV — one film, reciprocal competences MKCV encompasses several production paths. This text deepens the reference-to-scene profile: work with existing images or clips starts from that material, as described in the operating guide. **MKCV · beta, learning through use.** Mini Kernel Code Video is an evolving method. The examples explain how to work; observations of the film and corrections improve production and the knowledge for the next assignment. A film’s shared continuation preserves its subject, source status, current artifact and the question that can change it. Each specialist owns the knowledge and changes that belong to its work. A staging discovery may change the written scene; an edit may request another performance; an unavailable joint may change the intended gesture. Return the difference to that owner while keeping one recognizable film. Cinematic Screenwriting forms world, situation, action and authored words. Cinematic Direction forms the perceptible encounter through staging, camera and light. Character & Object Performance forms readable action and reaction. Film Montage forms the relationship between images and sound. Code production constructs and observes the actual executable medium. These public kits are available separately in the same collection. They can compose through a shared project guide without a required orchestration API, framework, crew size or fixed order. A file handoff must actually reach the receiver that uses it. Asset rights, public delivery and external actions keep their own authority. Keep the film and its editable files in the project. Use specializations through the available means and observe their combined result in the actual film. ## Optional technical example: renderer from an existing image ```python """A technical render example, not a semantic time-lapse storyboard. Make the reference image with an image generator first and save it as a local PNG. The real project's semantic transformation must be designed from its sources. """ from __future__ import annotations import argparse import shutil import subprocess from pathlib import Path from PIL import Image, ImageOps def frame_at(reference: Image.Image, t: float, duration: float, size: tuple[int, int]) -> Image.Image: """Render a code-built frame, using the generated image as a visible reference.""" w, h = size u = max(0.0, min(1.0, t / duration)) # Mild camera movement shows the rendering contract. Replace with a # source-grounded transformation; motion alone does not imply learning. zoom = 1.00 + 0.06 * (u * u * (3 - 2 * u)) enlarged = ImageOps.fit(reference, (round(w * zoom), round(h * zoom)), method=Image.Resampling.LANCZOS) left = round((enlarged.width - w) * (0.45 + 0.1 * u)) top = round((enlarged.height - h) / 2) return enlarged.crop((left, top, left+w, top+h)).convert('RGB') def main() -> None: parser = argparse.ArgumentParser(description='Reference-image to coded-frame rendering example') parser.add_argument('reference', type=Path, help='Image generated first using an image generator') parser.add_argument('--preview', type=Path, default=Path('first_frame_in_code.png')) parser.add_argument('--video', type=Path, default=None) parser.add_argument('--duration', type=float, default=30.0) parser.add_argument('--fps', type=int, default=24) parser.add_argument('--width', type=int, default=960) parser.add_argument('--height', type=int, default=540) args = parser.parse_args() if not args.reference.is_file(): parser.error('Provide an existing image created with the image generator') if args.duration <= 0 or args.fps <= 0 or args.width <= 0 or args.height <= 0: parser.error('Duration, fps and dimensions must be positive') if args.video and not shutil.which('ffmpeg'): parser.error('FFmpeg is required for MP4 export') reference = ImageOps.exif_transpose(Image.open(args.reference)).convert('RGB') size = (args.width, args.height) first = frame_at(reference, 0.0, args.duration, size) first.save(args.preview) if not args.video: print(f'Wrote coded first frame: {args.preview}') return total_frames = round(args.duration * args.fps) cmd = ['ffmpeg','-hide_banner','-loglevel','error','-y','-f','rawvideo','-pix_fmt','rgb24', '-s',f'{args.width}x{args.height}','-r',str(args.fps),'-i','-','-an', '-c:v','libx264','-pix_fmt','yuv420p',str(args.video)] encoder = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE) try: assert encoder.stdin is not None for i in range(total_frames): encoder.stdin.write(frame_at(reference, i/args.fps, args.duration, size).tobytes()) except (BrokenPipeError, Exception): encoder.kill() encoder.communicate() raise else: assert encoder.stdin is not None encoder.stdin.close() assert encoder.stderr is not None err = encoder.stderr.read().decode('utf-8', errors='replace') code = encoder.wait() if code: raise RuntimeError(f'FFmpeg exit {code}: {err}') print(f'Wrote {total_frames} frames: {args.video}') if __name__ == '__main__': main() ``` # Keep the film continuous when rendering stops When a render is long or interrupted, keep the intended timeline and render independently addressable frame intervals. Reuse a segment only after checking its inputs, code identity, frame count, dimensions, frame rate and decodability. A changed scene, asset or renderer calls for a new output identity. Segment boundaries are execution units; editing, gesture and narrative rhythm remain decisions about the film. ## Local use The supplied job selects only the original trusted renderer, with an explicit SHA256. FFmpeg and ffprobe must already be installed and reachable on PATH; the script does not download them. From the competence folder: ```sh cd examples/recoverable_video python -m venv .venv # Activate that environment with the command appropriate to your shell. python -m pip install -r requirements.txt python autostudio.py plan jobs/orbital_scene.json python autostudio.py run jobs/orbital_scene.json --max-chunks 1 python autostudio.py run jobs/orbital_scene.json python verify_recovery.py --output NEW_EMPTY_LOCATION ``` ## Interpret the continuation The first run returns `partial` and exit code 4: this is a controlled pause after one segment, not failure or a job left in the background. The second invocation of the same job verifies segments, completes the film and returns `completed`; another invocation returns `reused_verified`. `needs_capability_or_input` identifies missing means or inputs; `checkpoint_conflict` preserves earlier work when identity changed. Choose a new directory for changed work; do not delete checkpoints to bypass a mismatch. The four catalogue profiles need their own material; this package supplies a coded scene, not media for other examples. `reference_3d` executes an already-authored trusted local renderer with project-supplied inputs: it does not reconstruct an image automatically. ## Competences and evidence A technical checkpoint preserves verified work. The project guide preserves subject, sources, reasons, open choices and what the next contributor must understand. Use both when needed: resuming an encoder does not restore an assistant’s understanding or start a background agent. Observing the resulting film may still change the scene, method or chosen medium. The included coded-scene adapter was exercised in a Windows receiver with pause/resume, real process-tree interruption, damaged-segment repair and a continuous-render comparison. This does not establish narrative quality, image-to-3D fidelity, cross-host recovery or access to a media provider. The `examples/recoverable_video/VERIFICATION.json` report preserves the technical observation. The previous archive’s tests and media are not part of this kit. The supplied verification script exercises the local contract in a new directory. ## Optional included sources for an environment with local tools Save the named files with LF endings and exactly one final LF. The job selects the original renderer by SHA256. In a chat without tools, use the method and preserve the project continuation. ### examples/recoverable_video/autostudio.py ```python #!/usr/bin/env python3 """MKCV AutoStudio 0.3 — bounded local video executor. An AI's decision about story, direction and meaning belongs to the owner-native competences; this script only performs exact selected, authorized local effects. Standard library + Pillow, NumPy, OpenCV and local ffmpeg/ffprobe for supported profiles. """ from __future__ import annotations import argparse import hashlib import json import os import re import shutil import subprocess import sys import uuid from pathlib import Path from typing import Any VERSION = "0.3.2" PROFILES = { "coded_scene": {"mode": "executable_with_trusted_time_renderer", "owners": ["Cinematic Direction", "Character Performance", "Film Montage", "Code Medium"], "scope": "deterministic frame-addressable authored scene, verified segments and interruption recovery; not autonomous story generation"}, "animatic": {"mode": "executable", "owners": ["Editoriali", "Storyboard", "Film Montage", "Code Medium"], "scope": "timed stills and editorial camera motion; not character animation"}, "edit_existing": {"mode": "executable", "owners": ["Film Montage", "Sound", "Code Medium"], "scope": "re-encoded normalized clip montage; optional external music; no default source-audio reuse"}, "reference_3d": {"mode": "executable_with_trusted_renderer", "owners": ["Cinematic Direction", "Character Performance", "Code Medium"], "scope": "execute an already-authored trusted local renderer and compare its frame with a reference; no automatic 3D reconstruction"}, "image_motion": {"mode": "needs_assets_or_adapter", "owners": ["Character Performance", "Code Medium"], "scope": "requires subject layers, masks and reconstructed background"}, "procedural_3d_film": {"mode": "needs_scene_renderer", "owners": ["Cinematic Direction", "Character Performance", "Code Medium"], "scope": "requires an authored time-addressable 3D scene"}, "motion_graphics": {"mode": "needs_graphics_adapter", "owners": ["Editoriali", "Perceptual Composition", "Code Medium"], "scope": "requires data semantics and a renderer"}, "live_capture": {"mode": "needs_capture_receiver", "owners": ["Product Owner", "Direction", "Code Medium"], "scope": "requires true screen/software capture"}, "generative_video": {"mode": "needs_provider", "owners": ["Storyboard", "Direction", "Provider"], "scope": "requires connected provider, explicit cost/rights and actual invocation"}, "interactive_film": {"mode": "needs_interactive_runtime", "owners": ["UX-AI", "Design", "Code Medium"], "scope": "MP4 is not interactive software"}, } EXECUTABLE = {"animatic","edit_existing","reference_3d","coded_scene"} PROFILE_GAPS={ "image_motion": "Clean background, subject mask or rig plus an image-motion adapter not supplied", "procedural_3d_film": "Authored time-addressable scene renderer must be installed in a compatible receiver", "motion_graphics": "Domain data and code motion-graphics renderer required", "live_capture": "Real application/screen capture controller is not connected to this process", "generative_video": "Video-generation provider not connected; rights, credits and authority unresolved", "interactive_film": "Requires real interactive runtime, not an MP4 renderer" } class MKCVError(Exception): def __init__(self, code: str, message: str): super().__init__(message) self.code=code def hash_file(path: Path) -> str: h=hashlib.sha256() with path.open("rb") as fp: for chunk in iter(lambda: fp.read(1024*1024),b""): h.update(chunk) return h.hexdigest() def exec_process(cmd:list[str], timeout:int=120, *, cwd:Path|None=None, input_bytes:bytes|None=None) -> subprocess.CompletedProcess: try: p=subprocess.run(cmd, input=input_bytes, capture_output=True, cwd=cwd, timeout=timeout) except FileNotFoundError as exc: raise MKCVError("needs_capability_or_input", f"Executable missing: {cmd[0]}") from exc except subprocess.TimeoutExpired as exc: raise MKCVError("execution_timed_out", f"Process exceeded {timeout}s: {cmd[0]}") from exc if p.returncode: raise MKCVError("execution_failed", f"{cmd[0]} returned {p.returncode}: {p.stderr.decode('utf-8','replace')[-1500:]}") return p def probe(path:Path) -> dict[str,Any]: data=json.loads(exec_process(["ffprobe","-v","error","-count_frames","-show_format","-show_streams","-of","json",str(path)],timeout=120).stdout) video=next((s for s in data.get("streams",[]) if s.get("codec_type")=="video"),None) if not video: raise MKCVError("bad_artifact", f"No video stream: {path.name}") frames=video.get("nb_read_frames") or video.get("nb_frames") fps=video.get("avg_frame_rate") or "0/1" return {"codec":video.get("codec_name"),"width":video.get("width"),"height":video.get("height"), "fps":fps,"frames":int(frames) if frames and frames!='N/A' else None, "duration":float(data.get("format",{}).get("duration") or 0), "audio":any(s.get("codec_type")=="audio" for s in data.get("streams",[])), "audio_codec":next((s.get("codec_name") for s in data.get("streams",[]) if s.get("codec_type")=="audio"),None)} def decode_all(path:Path, timeout:int=140) -> None: exec_process(["ffmpeg","-hide_banner","-nostdin","-v","error","-xerror","-i",str(path),"-f","null","-"],timeout=timeout) def is_inside(path:Path,root:Path)->bool: return path==root or root in path.parents def work_path(root:Path, raw:str, *, existing:bool=True) -> Path: if not isinstance(raw,str) or not raw.strip(): raise MKCVError("invalid_job","Expected relative nonblank path") if Path(raw).is_absolute(): raise MKCVError("unsafe_path",f"Absolute path not allowed in job: {raw}") p=(root/raw).resolve() if not is_inside(p,root): raise MKCVError("unsafe_path", f"Path escapes job workspace: {raw}") if existing and (not p.is_file() or p.is_symlink()): raise MKCVError("needs_capability_or_input", f"Missing regular input file: {raw}") return p def require_int(value:Any,lo:int,hi:int,name:str)->int: if type(value) is not int or not lo<=value<=hi: raise MKCVError("invalid_job",f"{name} must be integer in [{lo},{hi}]") return value def select_profile(job:dict)->tuple[str|None,str|None]: requested=job.get("profile") if requested: if requested not in PROFILES: return None,"Unrecognized profile; cannot assume a video medium" return requested,None inputs=job.get("inputs",{}) matches=[] if isinstance(inputs,dict): if inputs.get("images"):matches.append("animatic") if inputs.get("clips"):matches.append("edit_existing") if inputs.get("renderer") and inputs.get("reference"):matches.append("reference_3d") if len(matches)==1:return matches[0],None return None,"Material or intent is insufficient or ambiguous; select a medium from capabilities" def load(job_path:Path,workspace:Path|None) -> tuple[dict,Path,Path]: job_path=job_path.resolve(strict=True) root=(workspace or (job_path.parent.parent if job_path.parent.name=='jobs' else job_path.parent)).resolve(strict=True) if not is_inside(job_path,root): raise MKCVError("unsafe_path", "Job file outside workspace") try: job=json.loads(job_path.read_text(encoding="utf-8")) except Exception as exc: raise MKCVError("invalid_job", f"Cannot parse job: {exc}") from exc if not isinstance(job,dict): raise MKCVError("invalid_job", "Job must be a JSON object") if job.get("id") and (not isinstance(job["id"],str) or not re.fullmatch(r"[\w-]{1,80}",job["id"], re.ASCII)): raise MKCVError("invalid_job","Job ID must use [A-Za-z0-9_-], max 80") if not isinstance(job.get("intent"),str) or not job["intent"].strip(): raise MKCVError("invalid_job","intent is required as substantive text") return job,root,job_path def plan_job(job:dict,root:Path)->dict: gaps=[]; warnings=[] profile,ambiguity=select_profile(job) if ambiguity: gaps.append(ambiguity) authority=job.get("authority",{}) if not isinstance(authority,dict): raise MKCVError("invalid_job","authority must be object") for eff in ("publish","spend","send","deploy"): if authority.get(eff): gaps.append(f"{eff} is an external effect: not authorized by the local video executor") inputs=job.get("inputs",{}) if not isinstance(inputs,dict):raise MKCVError("invalid_job","inputs must be object") out=job.get("output",{}) if not isinstance(out,dict):raise MKCVError("invalid_job","output must be object") width=require_int(out.get("width",640),160,1920,"output.width") height=require_int(out.get("height",360),90,1080,"output.height") if width%2 or height%2:raise MKCVError("invalid_job","width and height must be even (H.264 yuv420p)") fps=require_int(out.get("fps",24),1,60,"output.fps") max_frames=require_int(job.get("limits",{}).get("max_frames",1800),1,12000,"limits.max_frames") dest=work_path(root,out.get("directory",f"runs/{job.get('id','job')}/"),existing=False) asset_map={}; expected=0 def asset(label,path): p=work_path(root,path) if not p.exists(): gaps.append(f"Missing {label}: {path}") else:asset_map[label]={"path":str(p.relative_to(root)),"sha256":hash_file(p),"bytes":p.stat().st_size} return p if profile in PROFILE_GAPS:gaps.append(PROFILE_GAPS[profile]) if profile in EXECUTABLE: import importlib.util for cmd in ("ffmpeg","ffprobe"): if not shutil.which(cmd):gaps.append(f"Executable missing on this receiver: {cmd}") for module in ("PIL","numpy","cv2"): if importlib.util.find_spec(module) is None:gaps.append(f"Python dependency missing: {module}") if profile=="coded_scene": expected=require_int(inputs.get("frames"),1,12000,"inputs.frames") chunk_frames=require_int(inputs.get("chunk_frames",48),1,500,"inputs.chunk_frames") if chunk_frames>max_frames: gaps.append("chunk_frames exceeds max_frames") if not inputs.get("renderer"):gaps.append("coded_scene needs a trusted time-addressed renderer") else: try:asset("renderer",inputs["renderer"]) except MKCVError as e:gaps.append(str(e)) if authority.get("execute_trusted_renderer") is not True: gaps.append("authority.execute_trusted_renderer=true required for authored Python scene") sha=inputs.get("renderer_sha256") if not isinstance(sha,str) or not re.fullmatch("[a-f0-9]{64}",sha): gaps.append("coded_scene requires pinned renderer_sha256") elif "renderer" in asset_map and asset_map["renderer"]["sha256"]!=sha: gaps.append("Pinned renderer SHA256 differs from local file") assets=inputs.get("assets",[]) if not isinstance(assets,list):raise MKCVError("invalid_job","assets must be a list") for i,v in enumerate(assets): if not isinstance(v,str):raise MKCVError("invalid_job","assets entries must be paths") try:asset(f"asset_{i}",v) except MKCVError as e:gaps.append(str(e)) if inputs.get("audio"): try:asset("music",inputs["audio"]) except MKCVError as e:gaps.append(str(e)) if profile=="reference_3d": for n in ("reference","renderer","regions","camera"): if not inputs.get(n):gaps.append(f"Missing {n} for reference_3d") else: try:asset(n,inputs[n]) except MKCVError as e:gaps.append(str(e)) if authority.get("execute_trusted_renderer") is not True:gaps.append("authority.execute_trusted_renderer=true required for Python execution") if not re.fullmatch(r"[\w-]+\.png", inputs.get("render_name","reconstruction_R2.png"),re.ASCII): raise MKCVError("invalid_job","render_name must be a flat PNG filename") if not inputs.get("renderer_sha256"): gaps.append("Explicit renderer_sha256 pin required to execute trusted code") elif "renderer" in asset_map and inputs["renderer_sha256"]!=asset_map["renderer"]["sha256"]: gaps.append("Trusted renderer hash changed — explicit authority update needed") elif profile=="animatic": ims=inputs.get("images",[]) if not isinstance(ims,list) or not ims:gaps.append("animatic needs images[]") for i,im in enumerate(ims if isinstance(ims,list) else []): if not isinstance(im,dict):raise MKCVError("invalid_job",f"images[{i}] must be an object") frames=require_int(im.get("frames",48),1,1800,f"images[{i}].frames") expected+=frames try:asset(f"image_{i}",im["path"]) except (KeyError,MKCVError) as e:gaps.append(f"images[{i}]: {e}") if inputs.get("audio"): try:asset("music",inputs["audio"]) except MKCVError as e:gaps.append(str(e)) elif profile=="edit_existing": clips=inputs.get("clips",[]) if not isinstance(clips,list) or not clips:gaps.append("edit_existing needs clips[]") for i,clip in enumerate(clips if isinstance(clips,list) else []): if not isinstance(clip,dict):raise MKCVError("invalid_job",f"clips[{i}] must be an object") expected+=require_int(clip.get("frames",48),1,1800,f"clips[{i}].frames") require_int(clip.get("start_frame",0),0,10000000,f"clips[{i}].start_frame") try: path=asset(f"clip_{i}",clip["path"]) if path.exists(): p=probe(path) if p["frames"] and clip.get("start_frame",0)+clip.get("frames",48)>p["frames"]: gaps.append(f"clips[{i}]: selection exceeds original video frames") except (KeyError,MKCVError) as e:gaps.append(f"clips[{i}]: {e}") if inputs.get("audio"): try:asset("music",inputs["audio"]) except MKCVError as e:gaps.append(str(e)) else:warnings.append("Source clip audio is not copied by this adapter; output is silent unless music input is supplied") if expected>max_frames:gaps.append(f"Expected {expected} frames exceeds max_frames={max_frames}") executor_files=[Path(__file__).resolve()] if profile=="coded_scene":executor_files.append(Path(__file__).resolve().with_name("mkcv_resumable.py")) executor_sources={x.name:hash_file(x) for x in executor_files} job_signature={"job":job,"inputs":asset_map,"executor":VERSION,"executor_sources":executor_sources,"profile":profile} fingerprint=hashlib.sha256(json.dumps(job_signature,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode()).hexdigest() return {"status":"executable" if profile in EXECUTABLE and not gaps else "needs_capability_or_input", "profile":profile,"intent":job["intent"],"owners":PROFILES.get(profile,{}).get("owners",[]), "profile_note":PROFILES.get(profile,{}).get("scope"),"gaps":gaps,"warnings":warnings, "fingerprint":fingerprint,"executor_sources":executor_sources,"inputs":asset_map,"expected_frames":expected or None, "output":{"directory":str(dest.relative_to(root)),"width":width,"height":height,"fps":fps}} def crop_to_frame(img, width, height, progress:float, scale_from:float, scale_to:float, focus_x:float=.5, focus_y:float=.5): from PIL import Image import numpy as np s=scale_from+(scale_to-scale_from)*progress base=max(width/img.width,height/img.height) nw=max(width,int(round(img.width*base*s)));nh=max(height,int(round(img.height*base*s))) im=img.resize((nw,nh),Image.Resampling.LANCZOS) # Ease pan tied to progress, not to frame-count-dependent hidden state. ox=int((nw-width)*focus_x);oy=int((nh-height)*focus_y) ox=min(nw-width,max(0,ox));oy=min(nh-height,max(0,oy)) return im.crop((ox,oy,ox+width,oy+height)) def write_rgb_frames(frames, output:Path,width:int,height:int,fps:int, count:int) -> None: cmd=["ffmpeg","-hide_banner","-loglevel","error","-nostdin","-y","-f","rawvideo","-vcodec","rawvideo","-pix_fmt","rgb24", "-s",f"{width}x{height}","-r",str(fps),"-i","pipe:0","-an","-c:v","libx264","-preset","veryfast","-crf","21", "-pix_fmt","yuv420p","-threads","1","-movflags","+faststart",str(output)] import subprocess proc=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE) seen=0 try: for im in frames: if im.size!=(width,height):raise MKCVError("bad_frame",f"Expected {(width,height)}, got {im.size}") proc.stdin.write(im.convert("RGB").tobytes()) seen+=1 proc.stdin.close() err=proc.stderr.read() code=proc.wait(timeout=120) if code:raise MKCVError("execution_failed",f"ffmpeg exit {code}: {err.decode('utf-8','replace')[-1200:]}") if seen!=count:raise MKCVError("bad_artifact",f"Input frame count mismatch {seen} != {count}") except BaseException: if proc.stdin and not proc.stdin.closed:proc.stdin.close() proc.kill();proc.wait() raise def local_font(size:int): """Resolve a local font on this receiver; never require a private asset.""" from PIL import ImageFont for name in ("DejaVuSans.ttf", "Arial.ttf"): try: return ImageFont.truetype(name, size) except OSError: pass try: return ImageFont.load_default(size=size) except TypeError: return ImageFont.load_default() def generate_animatic(job:dict, root:Path, work:Path, width:int,height:int,fps:int)->tuple[Path,int]: from PIL import Image, ImageDraw, ImageFont from itertools import accumulate images=[]; total=0 for row in job["inputs"]["images"]: img=Image.open(work_path(root,row["path"])).convert("RGB") frames=row.get("frames",48) focus=row.get("focus",[.5,.5]); z=row.get("zoom",[1.0,1.04]) if not (isinstance(focus,list) and len(focus)==2 and all(type(x) in (int,float) and 0<=x<=1 for x in focus)): raise MKCVError("invalid_job","focus must be [0..1,0..1]") if not (isinstance(z,list) and len(z)==2 and all(type(x) in (int,float) and 1<=x<=1.6 for x in z)): raise MKCVError("invalid_job","zoom must be [1..1.6,1..1.6]") images.append((img,frames,focus,z,row.get("caption",""))) total+=frames # Editable accessibility companion for visible titles, never a transcript of spoken audio. def srt_time(frame:int)->str: ms=round(frame*1000/fps) h,ms=divmod(ms,3600000);m,ms=divmod(ms,60000);sec,ms=divmod(ms,1000) return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}" cues=[];cursor=0 for img,n,focus,z,caption in images: if caption: cues.append(f"{len(cues)+1}\n{srt_time(cursor)} --> {srt_time(cursor+n)}\n{caption}\n") cursor+=n if cues: (work/"visual_titles.srt").write_text("\n".join(cues)+"\n",encoding="utf-8") def frames(): for img,n,focus,z,caption in images: for i in range(n): t=i/max(1,n-1); smooth=t*t*(3-2*t) a=crop_to_frame(img,width,height,smooth,z[0],z[1],focus[0],focus[1]) if caption: draw=ImageDraw.Draw(a) from PIL import ImageFont font=local_font(max(16,round(height*.05))) limit=max(0,int(width*.84)) # Caption is editable overlay, not claimed to be in source image. while draw.textbbox((0,0),caption,font=font)[2]>limit and font.size>12: font=local_font(font.size-1) bb=draw.textbbox((0,0),caption,font=font) cx=(width-(bb[2]-bb[0]))//2; y=height-round(height*.11) draw.rounded_rectangle((max(0,cx-13),y-8,min(width,cx+bb[2]-bb[0]+13),y+bb[3]-bb[1]+14),radius=10,fill=(12,16,31)) draw.text((cx,y),caption,font=font,fill=(246,248,252)) yield a path=work/"video_only.mp4" write_rgb_frames(frames(),path,width,height,fps,total) return path,total def generate_edit(job:dict, root:Path, work:Path,width:int,height:int,fps:int)->tuple[Path,int]: paths=[];total=0 for i,clip in enumerate(job["inputs"]["clips"]): p=work_path(root,clip["path"]) num=clip.get("frames",48); start=clip.get("start_frame",0) part=work/f"part_{i:02d}.mp4" # Explicit output-frame sampling, with trim enforced after output fps normalization. vf=(f"fps={fps},trim=start_frame={start}:end_frame={start+num},setpts=PTS-STARTPTS," f"scale={width}:{height}:force_original_aspect_ratio=decrease," f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1") exec_process(["ffmpeg","-hide_banner","-nostdin","-v","error","-y","-i",str(p),"-vf",vf, "-an","-frames:v",str(num),"-c:v","libx264","-preset","veryfast","-crf","21","-pix_fmt","yuv420p", "-threads","1",str(part)],timeout=180) pr=probe(part) if pr["frames"]!=num:raise MKCVError("bad_artifact",f"Clip {i}: expected {num}, got {pr['frames']}") paths.append(part);total+=num # Reconstruct a strict CFR timeline instead of concatenating MP4 packets with # inherited container time bases (which can report an inaccurate avg FPS). video=work/"video_only.mp4" inputs=[] for item in paths: inputs.extend(["-i",str(item)]) labels=''.join(f"[{i}:v]" for i in range(len(paths))) exec_process(["ffmpeg","-hide_banner","-nostdin","-v","error","-y",*inputs, "-filter_complex",f"{labels}concat=n={len(paths)}:v=1:a=0[v]", "-map","[v]","-r",str(fps),"-fps_mode","cfr","-frames:v",str(total), "-an","-c:v","libx264","-preset","veryfast","-crf","21", "-pix_fmt","yuv420p","-threads","1",str(video)],timeout=180) return video,total def compare_reference(job:dict,root:Path, work:Path)->tuple[Path,None]: from PIL import Image,ImageDraw import numpy as np import cv2 inputs=job["inputs"] trusted=work_path(root,inputs["renderer"]) assert hash_file(trusted)==inputs["renderer_sha256"] shutil.copy2(trusted,work/"rebuild_reference.py") shutil.copy2(work_path(root,inputs["reference"]),work/"reference.png") shutil.copy2(work_path(root,inputs["camera"]),work/"scene_spec.json") shutil.copy2(work_path(root,inputs["regions"]),work/"regions.json") exec_process([sys.executable,str(work/"rebuild_reference.py")],cwd=work,timeout=150) output_name=inputs.get("render_name","reconstruction_R2.png") p=work/output_name if not p.is_file():raise MKCVError("bad_artifact",f"Renderer did not create {output_name}") ref=Image.open(work/"reference.png").convert("RGB") render=Image.open(p).convert("RGB") w,h=render.size; ref=ref.resize((w,h),Image.Resampling.LANCZOS) combo=Image.new("RGB",(w*2,h));combo.paste(ref);combo.paste(render,(w,0)) combo.save(work/"comparison.png") Image.blend(ref,render,.5).save(work/"overlay.png") spec=json.loads((work/"regions.json").read_text(encoding="utf-8"));results=[] if not isinstance(spec.get("regions"),list):raise MKCVError("invalid_job","regions must be array") ref_array=np.asarray(ref,dtype=np.float32); ren_array=np.asarray(render,dtype=np.float32) for i,r in enumerate(spec["regions"]): name=re.sub(r"[^A-Za-z0-9_-]","_",r.get("id",f"ROI{i}")) v=r["roi"] if len(v)!=4 or not all(0<=x<=1 for x in v) or v[0]>=v[2] or v[1]>=v[3]: raise MKCVError("invalid_job",f"Invalid ROI: {name}") coords=[int(a*b) for a,b in zip(v,[w,h,w,h])]; x0,y0,x1,y1=coords if x0==x1 or y0==y1:continue im=Image.new("RGB",((x1-x0)*2,y1-y0));im.paste(ref.crop(coords));im.paste(render.crop(coords),(x1-x0,0));im.save(work/f"roi_{i:02}_{name}.png") results.append({"region":name,"mean_abs_pixel_difference_descriptive_not_fidelity":round(float(np.abs(ref_array[y0:y1,x0:x1]-ren_array[y0:y1,x0:x1]).mean()),2)}) (work/"OBSERVATIONS.json").write_text(json.dumps({"status":"not_a_fidelity_certificate","camera_matched":"not_verified_automatically","regions":results},ensure_ascii=False,indent=2)) return p,None def mux_music(video:Path, audio:Path,out:Path, duration:float)->None: exec_process(["ffmpeg","-hide_banner","-nostdin","-v","error","-y","-i",str(video),"-i",str(audio), "-filter_complex",f"[1:a]apad,atrim=duration={duration:.7f}[a]", "-map","0:v:0","-map","[a]","-c:v","copy","-c:a","aac","-b:a","160k","-movflags","+faststart",str(out)],timeout=120) def contact_sheet(path:Path,out:Path, positions:tuple[float,...]=(.05,.25,.5,.75,.95)) -> None: from PIL import Image,ImageDraw import cv2 cap=cv2.VideoCapture(str(path)) n=int(cap.get(cv2.CAP_PROP_FRAME_COUNT));cells=[] for p in positions: cap.set(cv2.CAP_PROP_POS_FRAMES, min(n-1,int(round((n-1)*p)))) ok,frame=cap.read() if ok:cells.append(Image.fromarray(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)).resize((320,180))) cap.release() if cells: sheet=Image.new("RGB",(320*len(cells),180)); for i,img in enumerate(cells):sheet.paste(img,(320*i,0)) sheet.save(out,quality=90) def execute(job:dict, root:Path, plan:dict, *, max_chunks:int|None=None) -> dict: if max_chunks is not None and plan["profile"]!="coded_scene": raise MKCVError("invalid_job","--max-chunks is supported only for coded_scene") if plan["profile"]=="coded_scene": from mkcv_resumable import execute as execute_resumable return execute_resumable(job,root,plan,sys.modules[__name__],max_chunks=max_chunks) if plan["status"]!="executable":return {"status":"needs_capability_or_input","plan":plan} folder=work_path(root,plan["output"]["directory"],existing=False) if folder.exists(): receipt=folder/"EXECUTION.json" if receipt.exists(): try: prev=json.loads(receipt.read_text()) if prev.get("fingerprint")==plan["fingerprint"]: assets=prev.get("artifacts",{}) if all((folder/k).is_file() and hash_file(folder/k)==v["sha256"] for k,v in assets.items()): return {"status":"reused_verified","directory":plan["output"]["directory"],"receipt":prev} except (ValueError,KeyError):pass raise MKCVError("output_conflict","Destination exists but cannot prove matching job and intact files; select new output.directory") folder.parent.mkdir(parents=True,exist_ok=True) lock=folder.parent/("."+folder.name+".execution.lock") try: lock.mkdir() except FileExistsError as ex: raise MKCVError("execution_in_progress_or_stale_lock", "Another execution or an unresolved lock exists for this exact output; reconcile before retrying") from ex stage=folder.parent/("."+folder.name+".attempt-"+uuid.uuid4().hex[:8]);stage.mkdir() w=plan["output"]["width"];h=plan["output"]["height"];fps=plan["output"]["fps"] profile=plan["profile"] try: expected=plan["expected_frames"] if profile=="animatic": vid,expected=generate_animatic(job,root,stage,w,h,fps) elif profile=="edit_existing": vid,expected=generate_edit(job,root,stage,w,h,fps) elif profile=="reference_3d": vid,expected=compare_reference(job,root,stage) else:raise MKCVError("needs_capability_or_input",f"Profile not runnable: {profile}") if profile!="reference_3d": final=stage/"film.mp4" if job["inputs"].get("audio"): mux_music(vid,work_path(root,job["inputs"]["audio"]),final,expected/fps) else:shutil.copy2(vid,final) meta=probe(final) if meta["frames"]!=expected: raise MKCVError("bad_artifact",f"Decoded frame count {meta['frames']} != expected {expected}") if (meta["width"],meta["height"])!=(w,h):raise MKCVError("bad_artifact","Dimension mismatch") num,den=map(int,meta["fps"].split('/')) if den==0 or num!=fps*den:raise MKCVError("bad_artifact",f"Frame rate mismatch: {meta['fps']} != {fps}/1") decode_all(final) contact_sheet(final,stage/"contact_sheet.jpg") result={"video":meta,"expected_frames":expected,"decoded_without_errors":True,"claim":"technical_output_not_semantic_quality_certification"} # Normalized intermediate files are implementation detail: keep only deliverables. for file in stage.glob("part_*.mp4"):file.unlink() for name in ("video_only.mp4","concat.txt"): tmp=stage/name if tmp.exists():tmp.unlink() else: from PIL import Image x=Image.open(vid);x.verify() result={"still":{"width":x.width,"height":x.height},"decoded_without_errors":True,"claim":"model_rendered_not_reference_fidelity_certification"} artifacts={f.name:{"sha256":hash_file(f),"bytes":f.stat().st_size} for f in sorted(stage.iterdir()) if f.is_file() and f.name not in ("EXECUTION.json",)} receipt={"schema":"mkcv-execution-receipt/0.2","status":"completed","version":VERSION,"profile":profile, "job_id":job.get("id"),"fingerprint":plan["fingerprint"],"inputs":plan["inputs"],"result":result, "artifacts":artifacts,"limits":"local output only; no publication/spend/background execution"} (stage/"EXECUTION.json").write_text(json.dumps(receipt,ensure_ascii=False,indent=2,sort_keys=True)+"\n",encoding="utf-8") stage.rename(folder) return {"status":"completed","directory":plan["output"]["directory"],"receipt":receipt} except BaseException as e: (stage/"ATTEMPT.json").write_text(json.dumps({"status":"failed_without_claimed_output","code":getattr(e,"code",type(e).__name__),"message":str(e),"job_fingerprint":plan["fingerprint"]},ensure_ascii=False,indent=2),encoding="utf-8") raise finally: # The incomplete attempt survives for analysis; only the active lock ends. lock.rmdir() def main(): ap=argparse.ArgumentParser(description="MKCV AutoStudio — local, bounded, receipts-first media executor") ap.add_argument("command",choices=["catalog","plan","run"]) ap.add_argument("job",nargs="?",type=Path) ap.add_argument("--workspace",type=Path,default=None,help="Explicit workspace root; job and all assets must reside within it") ap.add_argument("--max-chunks",type=int,default=None,help="QA controlled suspension after this many newly rendered chunks (no background work)") args=ap.parse_args() try: if args.command=="catalog": print(json.dumps({"version":VERSION,"profiles":PROFILES,"implemented_profiles":sorted(EXECUTABLE)},ensure_ascii=False,indent=2));return if not args.job:raise MKCVError("invalid_job","Job path required") job,root,jobpath=load(args.job,args.workspace) plan=plan_job(job,root) obj=plan if args.command=="plan" else execute(job,root,plan,max_chunks=args.max_chunks) print(json.dumps(obj,ensure_ascii=False,indent=2,sort_keys=True)) if obj.get("status")=="partial":sys.exit(4) if obj.get("status") not in ("executable","completed","reused_verified"): sys.exit(3) except MKCVError as e: print(json.dumps({"status":e.code,"message":str(e)},ensure_ascii=False,indent=2),file=sys.stderr) sys.exit(2) except Exception as e: # Do not claim success; preserve the failed attempt and a machine-readable error. print(json.dumps({"status":"execution_failed","type":type(e).__name__,"message":str(e)},ensure_ascii=False,indent=2),file=sys.stderr) sys.exit(2) if __name__=="__main__": main() ``` ### examples/recoverable_video/mkcv_resumable.py ```python #!/usr/bin/env python3 """Resumable, receipt-backed video-chunk adapter for MKCV AutoStudio. The caller supplies a pinned, trusted, deterministic renderer that accepts: --start-frame N --end-frame M --fps F --width W --height H --output PATH Each invocation must make an H264/no-audio MP4 of exactly M-N frames. This module never invents scenes or selects unauthorized external effects. """ from __future__ import annotations import json import os import shutil import socket import sys import time import uuid from pathlib import Path from typing import Any def _atomic_json(dest:Path, data:dict) -> None: dest.parent.mkdir(parents=True, exist_ok=True) tmp=dest.with_name(dest.name+'.new-'+uuid.uuid4().hex[:8]) try: with tmp.open('w',encoding='utf-8') as f: json.dump(data,f,sort_keys=True,indent=2,ensure_ascii=False) f.write('\n');f.flush();os.fsync(f.fileno()) os.replace(tmp,dest) finally: if tmp.exists(): tmp.unlink() def _load_json(p:Path, a)->dict: try: data=json.loads(p.read_text(encoding='utf-8')) if not isinstance(data,dict):raise ValueError('not an object') return data except (OSError, ValueError, UnicodeError) as exc: raise a.MKCVError('checkpoint_invalid',f'Cannot trust {p.name}; preserve and review partial work: {exc}') from exc def _pid_alive(pid:int)->bool: if type(pid) is not int or pid<1:return False if os.name == "nt": # Windows signal 0 is CTRL_C_EVENT, not a process-existence query. # Wait on a query-only handle; never send a signal to inspect a lock. import ctypes from ctypes import wintypes api = ctypes.WinDLL("kernel32", use_last_error=True) api.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) api.OpenProcess.restype = wintypes.HANDLE api.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD) api.WaitForSingleObject.restype = wintypes.DWORD api.CloseHandle.argtypes = (wintypes.HANDLE,) api.CloseHandle.restype = wintypes.BOOL handle = api.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE only if not handle: return ctypes.get_last_error() != 87 # absent PID; otherwise unknown try: status = api.WaitForSingleObject(handle, 0) return status != 0 # WAIT_OBJECT_0 means terminated; unknown stays live finally: api.CloseHandle(handle) try:os.kill(pid,0);return True except ProcessLookupError:return False except PermissionError:return True def _lock_dir(lock:Path,a)->list[dict[str,Any]]: events=[] try:lock.mkdir() except FileExistsError: if lock.is_symlink() or not lock.is_dir():raise a.MKCVError('unsafe_path','Lock path is not a directory') state=_load_json(lock/'holder.json',a) if state.get('hostname')!=socket.gethostname(): raise a.MKCVError('execution_in_progress_or_unknown_lock','Cross-host or unidentified lock; do not steal') pid=state.get('pid') if _pid_alive(pid): raise a.MKCVError('execution_in_progress_or_stale_lock',f'Existing active renderer process {pid}') # This lock was held by a process that no longer exists on the same host. archived=lock.with_name(lock.name+'.stale-'+uuid.uuid4().hex[:8]) lock.rename(archived) events.append({'event':'stale_lock_reclaimed','old_pid':pid,'archive':archived.name}) try:lock.mkdir() except FileExistsError as exc:raise a.MKCVError('execution_in_progress_or_stale_lock','Concurrent restart') from exc _atomic_json(lock/'holder.json',{'pid':os.getpid(),'hostname':socket.gethostname(),'started':time.time()}) return events def _verify_chunk(path:Path,first:int,end:int,w:int,h:int,fps:int,a)->dict: if not path.is_file() or path.is_symlink():raise a.MKCVError('missing_chunk',f'Chunk missing/unsafe: {path.name}') info=a.probe(path) if info['codec']!='h264' or info['audio'] or (info['width'],info['height'])!=(w,h) or info['frames']!=end-first: raise a.MKCVError('invalid_chunk',f'{path.name}: wrong codec/dims/audio/frame count: {info}') num,den=map(int,info['fps'].split('/')) if den<=0 or num!=fps*den: raise a.MKCVError('invalid_chunk',f'{path.name}: FPS {info["fps"]} != {fps}') a.decode_all(path) return {'sha256':a.hash_file(path),'bytes':path.stat().st_size,'frames':end-first,'fps':info['fps'],'codec':'h264'} def _verified_reuse(dest:Path, plan:dict, a)->dict: rec=_load_json(dest/'EXECUTION.json',a) if rec.get('fingerprint')!=plan['fingerprint'] or rec.get('status')!='completed': raise a.MKCVError('output_conflict','Completed output belongs to another input, job or executor') records=rec.get('artifacts',{}) if not isinstance(records,dict) or not records or 'film.mp4' not in records: raise a.MKCVError('output_conflict','Completed receipt lacks verifiable media') for raw,datum in records.items(): p=dest/raw if p.is_symlink() or not p.is_file() or a.hash_file(p)!=datum.get('sha256'): raise a.MKCVError('output_conflict',f'Published local artifact missing/modified: {raw}') meta=a.probe(dest/'film.mp4') if meta.get('frames')!=plan['expected_frames'] or meta.get('codec')!='h264': raise a.MKCVError('output_conflict','Final video could not be verified') a.decode_all(dest/'film.mp4') return {'status':'reused_verified','directory':plan['output']['directory'],'receipt':rec} def execute(job:dict,root:Path,plan:dict,a,*,max_chunks:int|None=None)->dict: """Execute/resume chunks synchronously. max_chunks allows *controlled* suspend for QA.""" if plan['status']!='executable':return {'status':'needs_capability_or_input','plan':plan} if max_chunks is not None and (type(max_chunks) is not int or max_chunks<=0): raise a.MKCVError('invalid_job','max_chunks must be positive integer') dest=a.work_path(root,plan['output']['directory'],existing=False) if dest.is_symlink():raise a.MKCVError('unsafe_path','Final output is a symlink') if dest.exists(): return _verified_reuse(dest,plan,a) partial=dest.parent/('.'+dest.name+'.partial') lock=dest.parent/('.'+dest.name+'.execution.lock') if partial.is_symlink():raise a.MKCVError('unsafe_path','Partial output is a symlink') dest.parent.mkdir(parents=True,exist_ok=True) startup_events=_lock_dir(lock,a) try: inputs=job['inputs'];fps=plan['output']['fps'];w=plan['output']['width'];h=plan['output']['height'] count=plan['expected_frames'];chunk=inputs['chunk_frames'];segments=[(s,min(s+chunk,count)) for s in range(0,count,chunk)] if partial.exists(): state=_load_json(partial/'STATE.json',a) if state.get('fingerprint')!=plan['fingerprint'] or state.get('version')!=a.VERSION: raise a.MKCVError('checkpoint_conflict','Partial job has different inputs/owner/executor. Preserve old and select new output directory.') if state.get('segments_expected')!=[[s,e] for s,e in segments]: raise a.MKCVError('checkpoint_conflict','Partial segment schedule changed') for event in startup_events:state['events'].append(event) else: partial.mkdir() (partial/'segments').mkdir() (partial/'quarantine').mkdir() shutil.copy2(a.work_path(root,inputs['renderer']),partial/'scene_renderer.py') (partial/'assets').mkdir() for i,path in enumerate(inputs.get('assets',[])): shutil.copy2(a.work_path(root,path),partial/'assets'/f'{i:02d}_{Path(path).name}') state={'schema':'mkcv-chunk-checkpoint/0.3','version':a.VERSION,'fingerprint':plan['fingerprint'], 'profile':'coded_scene','expected_frames':count,'fps':fps,'width':w,'height':h, 'segments_expected':[[s,e] for s,e in segments], 'completed':{}, 'events':startup_events, 'source_renderer_sha256':plan['inputs']['renderer']['sha256'], 'source_assets':plan['inputs']} _atomic_json(partial/'STATE.json',state) # Pins are still valid at point of resume, including when the job includes external inputs. if a.hash_file(partial/'scene_renderer.py')!=plan['inputs']['renderer']['sha256']: raise a.MKCVError('checkpoint_conflict','Staged renderer changed from pinned source') for i,path in enumerate(inputs.get('assets',[])): if a.hash_file(partial/'assets'/f'{i:02d}_{Path(path).name}')!=plan['inputs'][f'asset_{i}']['sha256']: raise a.MKCVError('checkpoint_conflict','Staged asset changed') done_this_call=0; reused=0;created=0; repaired=0 for start,end in segments: key=f'{start:08d}_{end:08d}' name=f'part_{key}.mp4' movie=partial/'segments'/name current=state['completed'].get(key) valid=None if movie.exists(): try: valid=_verify_chunk(movie,start,end,w,h,fps,a) if current and (valid['sha256']!=current.get('sha256') or valid['bytes']!=current.get('bytes')): raise a.MKCVError('invalid_chunk','Recorded chunk digest differs') except (a.MKCVError,ValueError,KeyError,RuntimeError) as exc: reason=str(exc)[:250] q=partial/'quarantine'/(name+'.damaged-'+uuid.uuid4().hex[:8]) movie.rename(q) state['events'].append({'event':'invalid_chunk_quarantined','segment':key,'reason':reason,'quarantine':q.name}) repaired+=1;valid=None state['completed'].pop(key,None) current=None # It was quarantined, not an independent missing chunk. _atomic_json(partial/'STATE.json',state) if valid: if not current: # Crash after encode, before checkpoint write. Adopt only after full decode. state['events'].append({'event':'orphan_chunk_verified_and_adopted','segment':key}) state['completed'][key]=valid _atomic_json(partial/'STATE.json',state) reused+=1 continue if current and not movie.exists(): state['events'].append({'event':'missing_chunk_regenerated','segment':key}) repaired+=1 state['completed'].pop(key,None) _atomic_json(partial/'STATE.json',state) # Trusted time-addressable renderer executes only the local selected effect. cmd=[sys.executable,str(partial/'scene_renderer.py'),'--start-frame',str(start),'--end-frame',str(end), '--fps',str(fps),'--width',str(w),'--height',str(h),'--output',str(movie), '--asset-root',str(partial/'assets')] try: executed=a.exec_process(cmd,timeout=180,cwd=partial) (partial/'segments'/f'{key}.log').write_bytes(executed.stdout[-10000:]+b'\nSTDERR:\n'+executed.stderr[-10000:]) record=_verify_chunk(movie,start,end,w,h,fps,a) except BaseException as exc: state['events'].append({'event':'segment_failed','segment':key,'reason':str(exc)[:250]}) _atomic_json(partial/'STATE.json',state) raise state['completed'][key]=record state['events'].append({'event':'rendered_and_decoded','segment':key,'sha256':record['sha256']}) _atomic_json(partial/'STATE.json',state) created+=1;done_this_call+=1 if max_chunks is not None and done_this_call>=max_chunks and len(state['completed'])Image.Image: """Entire image depends only on absolute frame index and fixed seed.""" t=frame/fps y,x=np.mgrid[0:h,0:w].astype(np.float32) xx=x/w;yy=y/h soft=np.exp(-((xx-.72)**2/.24+(yy-.48)**2/.35)) b=np.zeros((h,w,3),dtype=np.float32) b[:,:,0]=7+24*yy+15*soft; b[:,:,1]=12+15*yy+18*soft; b[:,:,2]=36+36*yy+29*soft # Gently moving atmospheric glow: procedural 2D space art, NOT a star chart. wave=np.exp(-((yy-(.72+.04*np.sin(xx*8-t*.25)))**2)/.018) b[:,:,0]+=7*wave; b[:,:,1]+=13*wave; b[:,:,2]+=29*wave im=Image.fromarray(np.uint8(np.clip(b,0,255)),mode='RGB').convert('RGBA') d=ImageDraw.Draw(im,'RGBA') for sx,sy,power,phase in STARS: starx=int(((sx + .008*t*(.3+sy))%1)*w);stary=int(sy*h) v=max(0.08,0.6+0.4*math.sin(phase+t*(1+sy*.8))) r=1.7 if power>.84 else 1 d.ellipse((starx-r,stary-r,starx+r,stary+r),fill=(182,209,255,int(70+140*v*power))) # Planet is a code-constructed 2.5D sphere with a moving terminator. cx=w*.74;cy=h*.53;R=h*.325 py,px=np.mgrid[0:h,0:w] dx=(px-cx)/R; dy=(py-cy)/R rad2=dx*dx+dy*dy; mask=rad2<=1 nz=np.sqrt(np.clip(1-rad2,0,1)) light=.31+.69*np.clip(-dx*.58-dy*.18+nz*.7,0,1) bands=(np.sin((dy+.3)*13.5+np.sin(dx*6+t*.025)*.6)+1)/2 stripes=.22*np.sin(dy*31+dx*5+1.3) pc=np.zeros((h,w,4),dtype=np.uint8) pc[:,:,0]=np.uint8(np.clip((30+64*bands+44*stripes)*light,0,255)) pc[:,:,1]=np.uint8(np.clip((84+70*bands)*light,0,255)) pc[:,:,2]=np.uint8(np.clip((143+94*bands-22*stripes)*light+36*nz,0,255)) pc[:,:,3]=np.where(mask,255,0) # Planetary atmosphere, low-key and stylized. gl=Image.new('RGBA',(w,h));g=ImageDraw.Draw(gl,'RGBA') for k in range(13,0,-1): gr=R+k*(h/330) g.ellipse((cx-gr,cy-gr,cx+gr,cy+gr),outline=(42,179,243,int(5+4*(14-k))),width=2) gl=gl.filter(ImageFilter.GaussianBlur(6)) im=Image.alpha_composite(im,gl) # Back ring, planet, front ring; depth suggested through deliberate occlusion. ring=Image.new('RGBA',(w,h));dr=ImageDraw.Draw(ring,'RGBA') for j in range(15): rr=R*(1.15+j*.034) box=(cx-rr*1.38,cy-rr*.34,cx+rr*1.38,cy+rr*.34) dr.arc(box,181,359,fill=(106+j*4,164+j*2,211+j,int(47+4*j)),width=1) im=Image.alpha_composite(im,ring) im=Image.alpha_composite(im,Image.fromarray(pc,mode='RGBA')) front=Image.new('RGBA',(w,h));df=ImageDraw.Draw(front,'RGBA') for j in range(15): rr=R*(1.15+j*.034) box=(cx-rr*1.38,cy-rr*.34,cx+rr*1.38,cy+rr*.34) df.arc(box,1,179,fill=(119+j*4,176+j*2,205+j,int(43+5*j)),width=1) im=Image.alpha_composite(im,front) d=ImageDraw.Draw(im,'RGBA') # Small spacecraft scanning the atmosphere: fictional orbital motion. sx=w*(.31+.038*math.sin(t*.53));sy=h*(.46+.063*math.cos(t*.71));angle=.16*math.sin(t*.7) # a connecting beam grows near the middle of the film, tied to time and scene geometry progress=min(1,max(0,(t-1.9)/1.1));fade=max(0,min(1,(4.7-t)/.7)) if progress>0: endpoint=(cx-R*.65,cy-R*.13) ex=sx+(endpoint[0]-sx)*progress;ey=sy+(endpoint[1]-sy)*progress beam=Image.new('RGBA',(w,h));bd=ImageDraw.Draw(beam,'RGBA') bd.line((sx,sy,ex,ey),fill=(28,192,243,int(70*fade)),width=9) beam=beam.filter(ImageFilter.GaussianBlur(9)); im=Image.alpha_composite(im,beam) d=ImageDraw.Draw(im,'RGBA');d.line((sx,sy,ex,ey),fill=(134,239,253,int(235*fade)),width=2) if progress>.99: glowR=12+3*math.sin((t-2.9)*5) d.ellipse((ex-glowR,ey-glowR,ex+glowR,ey+glowR),outline=(79,236,232,int(140*fade)),width=2) # Spacecraft facets, arranged around a rotated central body. def rot(qx,qy):return sx+qx*math.cos(angle)-qy*math.sin(angle),sy+qx*math.sin(angle)+qy*math.cos(angle) solar1=[rot(u,v) for u,v in [(-44,-13),(-17,-13),(-17,13),(-44,13)]] solar2=[rot(u,v) for u,v in [(17,-13),(44,-13),(44,13),(17,13)]] for panel in (solar1,solar2): d.polygon(panel,fill=(18,90,143,255),outline=(83,230,255,240)) for k in range(1,4): xx1=panel[0][0]+(panel[1][0]-panel[0][0])*k/4 xx2=panel[3][0]+(panel[2][0]-panel[3][0])*k/4 d.line((xx1,panel[0][1],xx2,panel[3][1]),fill=(122,211,239,115),width=1) d.line((*rot(-18,0),*rot(18,0)),fill=(199,215,240,255),width=4) d.ellipse((*rot(-13,-11),*rot(13,11)),fill=(229,235,244,255),outline=(102,203,245,255),width=2) d.ellipse((sx-3,sy-3,sx+3,sy+3),fill=(33,241,233,255)) d.line((*rot(0,-11),*rot(0,-24)),fill=(158,211,233,250),width=2) # Title holds the human meaning, not fake software UI or measured telemetry. f1=font_at(max(15,int(h*.062)),True) f2=font_at(max(11,int(h*.035))) f3=font_at(max(9,int(h*.026))) d.text((w*.06,h*.105),'MONDI IN CODICE',fill=(244,251,255,255),font=f1) d.text((w*.06,h*.105+h*.09),'Una scena prende movimento',fill=(157,228,245,250),font=f2) d.line((w*.06,h*.255,w*.18,h*.255),fill=(71,209,229,220),width=3) d.text((w*.06,h*.91),'MKCV / VISUALIZZAZIONE ORIGINALE',fill=(140,183,212,230),font=f3) return im.convert('RGB') def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--start-frame',type=int,required=True) p.add_argument('--end-frame',type=int,required=True) p.add_argument('--fps',type=int,required=True) p.add_argument('--width',type=int,required=True) p.add_argument('--height',type=int,required=True) p.add_argument('--output',type=Path,required=True) p.add_argument('--asset-root',type=Path,required=True) a=p.parse_args() if a.start_frame<0 or a.end_frame<=a.start_frame or a.end_frame-a.start_frame>1000: p.error('Invalid segment range') if a.width>1920 or a.height>1080 or a.width%2 or a.height%2 or a.fps>60: p.error('Invalid scene parameters') a.output.parent.mkdir(parents=True,exist_ok=True) cmd=['ffmpeg','-hide_banner','-nostdin','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24', '-s',f'{a.width}x{a.height}','-r',str(a.fps),'-i','pipe:0','-an','-c:v','libx264', '-preset','veryfast','-crf','21','-threads','1','-pix_fmt','yuv420p','-movflags','+faststart',str(a.output)] proc=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE) try: for i in range(a.start_frame,a.end_frame): frame=render_frame(i,a.fps,a.width,a.height) proc.stdin.write(frame.tobytes()) proc.stdin.close() err=proc.stderr.read();code=proc.wait(timeout=100) if code:raise RuntimeError(err.decode('utf8','replace')[-1300:]) except BaseException: if proc.stdin and not proc.stdin.closed:proc.stdin.close() proc.kill();proc.wait();raise if __name__=='__main__':main() ``` ### examples/recoverable_video/jobs/orbital_scene.json ```json { "id": "orbital-example", "intent": "Original illustrative coded scene: exercise local rendering continuity, not observational astronomy or an image-generated reference.", "profile": "coded_scene", "authority": { "execute_trusted_renderer": true }, "inputs": { "renderer": "fixtures/orbital_scene.py", "renderer_sha256": "9fa06e63db4dd8d3ec16b11dc55aa37a4366fc40e34dd510990beb363757dd04", "frames": 72, "chunk_frames": 12 }, "limits": { "max_frames": 120 }, "output": { "directory": "runs/orbital-example", "width": 320, "height": 180, "fps": 24 } } ``` ### examples/recoverable_video/verify_recovery.py ```python """Exercise a local recovery contract in a new, explicitly selected directory.""" import argparse import hashlib import importlib.util import json from pathlib import Path import shutil import subprocess import sys sys.dont_write_bytecode=True def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--output',type=Path,required=True,help='New directory; existing work is never overwritten') args=parser.parse_args();root=args.output.resolve();root.mkdir(parents=True,exist_ok=False) source=Path(__file__).resolve().parent (root/'fixtures').mkdir();(root/'jobs').mkdir() for name in ['autostudio.py','mkcv_resumable.py','fixtures/orbital_scene.py']: shutil.copyfile(source/name,root/name) spec=importlib.util.spec_from_file_location('recovery_adapter',root/'mkcv_resumable.py') module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(30)']) try: assert module._pid_alive(child.pid) and child.poll() is None child.kill();child.wait();assert not module._pid_alive(child.pid) finally: if child.poll() is None:child.kill();child.wait() original=json.loads((source/'jobs/orbital_scene.json').read_text(encoding='utf-8')) path=root/'jobs/orbital_scene.json' def run(job,label,partial=False,expected=0): path.write_text(json.dumps(job,ensure_ascii=False)+'\n',encoding='utf-8') command=[sys.executable,str(root/'autostudio.py'),'run',str(path),'--workspace',str(root)] if partial:command+=['--max-chunks','1'] result=subprocess.run(command,capture_output=True,timeout=180) (root/(label+'.stdout.json')).write_bytes(result.stdout) (root/(label+'.stderr.txt')).write_bytes(result.stderr) if result.returncode!=expected: raise RuntimeError(label+': '+result.stderr.decode('utf-8','replace')) return json.loads(result.stdout or result.stderr) first=run(original,'pause',partial=True,expected=4);assert first['status']=='partial' changed=dict(original);changed['inputs']=dict(original['inputs'],frames=84) assert run(changed,'changed-job',expected=2)['status']=='checkpoint_conflict' final=run(original,'resume');assert final['receipt']['result']['chunk_reused_this_call']==1 assert run(original,'reuse')['status']=='reused_verified' clean=dict(original);clean['id']='continuous';clean['output']=dict(original['output'],directory='runs/continuous') run(clean,'continuous') video=root/original['output']['directory']/'film.mp4' digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() assert digest(video)==digest(root/'runs/continuous/film.mp4') proof={'state':'passed','scope':'local process liveness, controlled pause/resume, changed-job refusal, completed reuse and exact video comparison','platform':sys.platform,'video_sha256':digest(video),'video':str(video)} (root/'VERIFICATION.json').write_text(json.dumps(proof,indent=2)+'\n',encoding='utf-8') print(json.dumps(proof)) if __name__=='__main__':main() ``` My assignment, sources, available means and requested result: