Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

test: first full from-zero reconstruction, delivered with its project

rpone17f4f437c5dd
diff --git a/examples/reference-reconstruction/README.md b/examples/reference-reconstruction/README.md
new file mode 100644
index 00000000..f12be0e2
--- /dev/null
+++ b/examples/reference-reconstruction/README.md
@@ -0,0 +1,31 @@
+# Reference reconstruction: ranking-typewriter video
+
+Reverse-engineered from `/Users/you/Downloads/ranking-typewriter-video.mp4` (45 s, 20 shots).
+
+Sources: `main.svml`, `studio.svs`, `build.svrun`, `hypit.runtime.json`, and the project-local package
+`@hypit/local-linerank` (owns the paper ranking board; nothing installed expressed it).
+
+## Accepted deviations
+
+Recorded rather than hidden, because a difference nobody wrote down reads afterwards as a difference
+nobody noticed. Each of these is a place where the reconstruction does not match the reference, with
+the reason it was accepted as-is.
+
+- **Caption appearance is a guess.** Observations described it inconsistently — heavy outline+shadow
+ in one shot, a black rounded pill in two others. Chose bold white sans with a black stroke and a
+ translucent pill; not verified against the reference frame.
+- **Board title's mixed typography is a single face.** The reference's title runs a serif-italic
+ line and a sans-bold line; the package takes one font. Used `shadows-into-light` for both.
+- **The hand-drawn circle is a closed oval.** The reference is an unclosed black hand-drawn curve;
+ approximated with a wobbly closed oval (irregular radius, slight rotation).
+- **No typewriter click SFX.** One boundary observation mentioned it; all audio observations were
+ pure speech, and no tick asset exists. Not authored.
+- **Speaker framing is one image across all takes.** The reference cuts between medium and close
+ framings; simplified to a single reference image.
+- **The board background followed the blind comparison, not the observation.** One observation said
+ lined paper with a pink margin; the blind comparison and a pixel check showed grey graph-paper grid
+ with no pink line. Implemented the grid.
+
+The board was the only element that could be rendered without paid generation; it received two blind
+comparison rounds against the reference `shot-015` frame and was stopped at the two-attempt ceiling
+with the deviations above still present.
diff --git a/examples/reference-reconstruction/build.svrun b/examples/reference-reconstruction/build.svrun
new file mode 100644
index 00000000..d22b48b0
--- /dev/null
+++ b/examples/reference-reconstruction/build.svrun
@@ -0,0 +1,8 @@
+<?svml using="@hypit/run-markup@1"?>
+
+<svrun version="1">
+ <author source="./main.svml"/>
+
+ <target output="final.video"/>
+
+</svrun>
diff --git a/examples/reference-reconstruction/hypit.runtime.json b/examples/reference-reconstruction/hypit.runtime.json
new file mode 100644
index 00000000..24236361
--- /dev/null
+++ b/examples/reference-reconstruction/hypit.runtime.json
@@ -0,0 +1,43 @@
+{
+ "format": "hypit.runtime-profile@1",
+ "runtime": {
+ "use": "@hypit/runtime-local",
+ "config": {
+ "dataRoot": ".hypit/runtimes/local",
+ "artifacts": { "use": "@hypit/artifact-store-fs", "config": { "path": "artifacts" } },
+ "credentials": {
+ "environment": { "use": "@hypit/credential-store-env" }
+ },
+ "endpoints": {
+ "kie.reference-reconstruction": {
+ "use": "@hypit/provider-kie",
+ "config": {
+ "apiKey": { "store": "env", "key": "KIE_API_KEY" },
+ "defaultConcurrency": 2
+ }
+ },
+ "media.reference-reconstruction": {
+ "use": "@hypit/provider-media-local",
+ "config": { "defaultConcurrency": 2 }
+ },
+ "whisperx.reference-reconstruction": {
+ "use": "@hypit/provider-whisperx-local",
+ "config": { "defaultConcurrency": 1 }
+ },
+ "vertex.reference-reconstruction": {
+ "use": "@hypit/provider-google-vertex",
+ "config": {
+ "projectEnv": "GOOGLE_CLOUD_PROJECT",
+ "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },
+ "location": "global",
+ "defaultConcurrency": 1
+ }
+ },
+ "hyperframes.reference-reconstruction": {
+ "use": "@hypit/provider-hyperframes-local",
+ "config": { "workers": 2, "quality": "standard", "defaultConcurrency": 1 }
+ }
+ }
+ }
+ }
+}
diff --git a/examples/reference-reconstruction/kits/speaker-v1.svs b/examples/reference-reconstruction/kits/speaker-v1.svs
new file mode 100644
index 00000000..4537dd20
--- /dev/null
+++ b/examples/reference-reconstruction/kits/speaker-v1.svs
@@ -0,0 +1,136 @@
+<?svml using="@hypit/text/svs@1"?>
+
+<sheet version="1" id="speaker-v1">
+ text-template.speaker-v1 {
+ separator: paragraph;
+ default-composition-stability: soft-locked;
+ default-camera-motion: none;
+ default-edit-rhythm: continuous-take;
+ default-performance: natural-explainer;
+ default-gesture: natural;
+ }
+
+ text-template.speaker-v1.block.base {
+ kind: fixed;
+ order: 10;
+ text: "Create a realistic vertical phone-shot talking-head video. @image1 is the visible speaker and scene reference. Preserve the person's identity, face, outfit, setting, lighting, lens feel, and broad composition. @audio1 is the speaker's voice-timbre reference.";
+ }
+
+ text-template.speaker-v1.block.script-contract {
+ kind: fixed;
+ order: 20;
+ text: "Deliver the supplied script exactly in order with clear lip-sync. The visible person speaks every line. Do not rewrite, summarize, add, remove, or reorder words.";
+ }
+
+ text-template.speaker-v1.block.composition-stability {
+ kind: axis;
+ order: 30;
+ parameter: composition-stability;
+ }
+
+ text-template.speaker-v1.choice.composition-stability.flexible-ugc {
+ text: "COMPOSITION: preserve the reference person and setup while allowing normal lively creator-video framing variation.";
+ }
+
+ text-template.speaker-v1.choice.composition-stability.soft-locked {
+ text: "COMPOSITION: keep the speaker in the same general region and preserve the reference composition, allowing natural posture changes and tiny crop or scale breathing.";
+ }
+
+ text-template.speaker-v1.choice.composition-stability.strict-locked {
+ text: "COMPOSITION: preserve subject placement, perspective, left-right orientation, background relationship, and framing envelope throughout the shot.";
+ }
+
+ text-template.speaker-v1.block.camera-motion {
+ kind: axis;
+ order: 40;
+ parameter: camera-motion;
+ }
+
+ text-template.speaker-v1.choice.camera-motion.none {
+ text: "CAMERA: hold a steady fixed framing.";
+ }
+
+ text-template.speaker-v1.choice.camera-motion.subtle-punch-in-return {
+ text: "CAMERA: use one subtle push-in on the most important phrase, then return smoothly to the original framing.";
+ }
+
+ text-template.speaker-v1.block.edit-rhythm {
+ kind: axis;
+ order: 50;
+ parameter: edit-rhythm;
+ }
+
+ text-template.speaker-v1.choice.edit-rhythm.continuous-take {
+ text: "EDIT RHYTHM: one continuous creator explanation with natural breath timing.";
+ }
+
+ text-template.speaker-v1.choice.edit-rhythm.pause-trim-jump-cuts {
+ text: "EDIT RHYTHM: polished pause-trim jump cuts at phrase boundaries while keeping the framing coherent.";
+ }
+
+ text-template.speaker-v1.block.performance {
+ kind: axis;
+ order: 60;
+ parameter: performance;
+ }
+
+ text-template.speaker-v1.choice.performance.natural-explainer {
+ text: "PERFORMANCE: natural explainer energy with clear eye focus, expressive eyebrows, small nods, and a friendly conversational rhythm.";
+ }
+
+ text-template.speaker-v1.choice.performance.high-energy-ugc {
+ text: "PERFORMANCE: vivid high-energy short-form delivery with expressive face changes on key words.";
+ }
+
+ text-template.speaker-v1.choice.performance.calm-authority {
+ text: "PERFORMANCE: composed, confident, precise, and trustworthy, with deliberate emphasis.";
+ }
+
+ text-template.speaker-v1.choice.performance.reactive-playful {
+ text: "PERFORMANCE: playful and reactive, with amused looks, quick smiles, skeptical eyebrows, and lively timing.";
+ }
+
+ text-template.speaker-v1.block.gesture {
+ kind: axis;
+ order: 70;
+ parameter: gesture;
+ }
+
+ text-template.speaker-v1.choice.gesture.restrained {
+ text: "GESTURE: restrained body language; let face, eyes, and voice carry the meaning.";
+ }
+
+ text-template.speaker-v1.choice.gesture.compact {
+ text: "GESTURE: compact explanatory hand movement close to the torso and inside the frame.";
+ }
+
+ text-template.speaker-v1.choice.gesture.natural {
+ text: "GESTURE: natural creator gestures such as open palms, small pointing beats, nods, and posture shifts where the script calls for them.";
+ }
+
+ text-template.speaker-v1.choice.gesture.expressive {
+ text: "GESTURE: richer hand, shoulder, and posture changes that support the spoken idea while remaining physically coherent.";
+ }
+
+ text-template.speaker-v1.block.hygiene {
+ kind: fixed;
+ order: 80;
+ text: "Keep face, hands, skin texture, lighting, and motion photoreal and stable. Add no subtitles, captions, labels, logos, UI text, floating words, or other readable on-screen text.";
+ }
+
+ text-template.speaker-v1.block.dialogue {
+ kind: slot;
+ order: 90;
+ slot: dialogue;
+ optional: false;
+ label: "SCRIPT TO DELIVER:";
+ }
+
+ text-template.speaker-v1.block.action {
+ kind: slot;
+ order: 100;
+ slot: action;
+ optional: true;
+ label: "ACTION DIRECTION:";
+ }
+</sheet>
diff --git a/examples/reference-reconstruction/main.svml b/examples/reference-reconstruction/main.svml
new file mode 100644
index 00000000..9abb7698
--- /dev/null
+++ b/examples/reference-reconstruction/main.svml
@@ -0,0 +1,188 @@
+<?svml using="@hypit/markup@1"?>
+
+<svml>
+ <import from="@hypit/script@1"/>
+ <import as="wording" from="@hypit/text@1"/>
+ <import as="media" from="@hypit/media@1"/>
+ <import as="estimate" from="@hypit/estimate@1"/>
+ <import as="gpt" from="@hypit/gpt-image@1"/>
+ <import as="seedance" from="@hypit/seedance@1"/>
+ <import as="speech" from="@hypit/speech-spine@1"/>
+ <import as="whisperx" from="@hypit/whisperx@1"/>
+ <import as="caption" from="@hypit/caption@1"/>
+ <import as="caption-fine" from="@hypit/caption-fine@1"/>
+ <import as="caption-ai" from="@hypit/caption-gemini@1"/>
+ <import as="fonts" from="@hypit/fonts-open@1"/>
+ <import as="space" from="@hypit/spatial@1"/>
+ <import as="media-track" from="@hypit/media-track@1"/>
+ <import as="film" from="@hypit/film@1"/>
+ <import as="render" from="@hypit/render-hyperframes@1"/>
+ <import as="linerank" from="@hypit/local-linerank@1"/>
+ <import as="studio" source="./studio.svs"/>
+ <import as="speaker-kit" source="./kits/speaker-v1.svs"/>
+
+ <!-- The complete spoken truth of the reference, segmented so every take is at the Seedance floor. -->
+ <script id="story">
+ <hook>
+ <HOST> Here are the top five most popular ways to learn AI. @board @reveal! Number five is Instagram. @/board It's mostly just viral AI memes, zero actual education on how to use this stuff for real work.
+ </hook>
+
+ <courses>
+ <HOST> @board @reveal! Number four, AI courses. @/board Courses can't keep up with how fast AI is progressing. They're all outdated by the time you finish the course.
+ </courses>
+
+ <youtube>
+ <HOST> @board @reveal! Number three, YouTube. @/board Every video is, @thumb this will change everything, @/thumb but it's just another sponsorship deal.
+ </youtube>
+
+ <twitter>
+ <HOST> @board @reveal! Number two, Twitter, @/board smart people share gold here, but you're gonna end up wasting two plus hours every day scrolling through bots to find what's actually meaningful, and no one has time for that.
+ </twitter>
+
+ <rundown>
+ <HOST> @board @reveal! Number one is the rundown, @done! @/board it's a free newsletter, it takes five minutes to read, and @product it actually teaches you the AI tools that really matter, and this is how two million people at companies like Apple, Microsoft, and NASA, well they use this to keep up with AI. @/product I added the link to this post if you wanna sign up for free.
+ </rundown>
+ </script>
+
+ <!-- Author-owned reference material: the single filmed location and the two evidence inserts. -->
+ <wording:Value id="speaker-scene-prompt">
+ A photograph with the texture of real iPhone footage. Generate a vertical seated medium close-up, as one frame cut out of video actually shot on an iPhone: genuinely real rather than glossy, carrying the texture of video and not of a posed photograph. The background stays clearly visible, with no depth-of-field blur. Skin texture is fine and real, the light is natural, and no part of the picture is broken. One man in his thirties with short dark hair and clear-framed glasses, wearing a black zip-up jacket and large black over-ear headphones, seated at a desk and turned slightly to his left, speaking into a black microphone on a boom arm. Behind him to the left is a dark muted purplish-brown wall with a softly glowing warm yellowish-orange rectangular light; behind him to the right is a bright computer monitor showing an out-of-focus image of large pink amoeba-like shapes against a bright blue background, with a horizontal streak of warm yellow light below it. Chest-up framing, subject centered.
+ </wording:Value>
+ <wording:Value id="product-ui-prompt">
+ A clean vertical mobile phone screen showing an AI newsletter called "The Rundown": a bold black masthead reading "THE RUNDOWN" at the top, then a section labeled "Latest Developments", a section labeled "Quick Hits", a section labeled "Trending AI Tools", and one step-by-step tutorial card. Black text on a white background, modern editorial layout, clean sans-serif type. No other readable text.
+ </wording:Value>
+ <wording:Value id="thumb-prompt">
+ A YouTube-style clickbait thumbnail in vertical 9:16 crop: a surprised man's face on the left, bold yellow uppercase text "THIS WILL CHANGE EVERYTHING" on the right, a red play-button triangle in the lower center, high contrast saturated colors. No other readable text.
+ </wording:Value>
+
+ <gpt:Image id="speaker-scene" prompt={speaker-scene-prompt} aspect-ratio="9:16" resolution="2K"/>
+ <gpt:Image id="product-ui" prompt={product-ui-prompt} aspect-ratio="9:16" resolution="2K"/>
+ <gpt:Image id="thumb-image" prompt={thumb-prompt} aspect-ratio="9:16" resolution="2K"/>
+
+ <!-- Per-take performance remains ordinary authored Text, separate from spoken words. -->
+ <wording:Value id="hook-action">
+ Open with direct eye contact and a friendly conversational tone, then lean in slightly for the reveal of number five.
+ </wording:Value>
+ <wording:Value id="courses-action">
+ Keep a dry, mildly dismissive tone for courses; use one compact dismissive hand wave.
+ </wording:Value>
+ <wording:Value id="youtube-action">
+ Raise an eyebrow and give a knowing skeptical look at the sponsorship punchline.
+ </wording:Value>
+ <wording:Value id="twitter-action">
+ Gesture to count off hours, then shake your head slightly at the time-wasting cost.
+ </wording:Value>
+ <wording:Value id="rundown-action">
+ Brighten and speak warmly and confidently about the number one pick, then close with a friendly call-to-action.
+ </wording:Value>
+
+ <!-- Duration remains an explicit graph fact derived from the pronunciation projection. -->
+ <estimate:Speech id="hook-duration" source={story.segment.hook.speech} policy={studio.speech.normal}/>
+ <estimate:Speech id="courses-duration" source={story.segment.courses.speech} policy={studio.speech.normal}/>
+ <estimate:Speech id="youtube-duration" source={story.segment.youtube.speech} policy={studio.speech.normal}/>
+ <estimate:Speech id="twitter-duration" source={story.segment.twitter.speech} policy={studio.speech.normal}/>
+ <estimate:Speech id="rundown-duration" source={story.segment.rundown.speech} policy={studio.speech.normal}/>
+
+ <!-- Prompt assembly is an ordinary Text subgraph; one speaking take per segment. -->
+ <wording:Render id="hook-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>
+ <wording:Set name="dialogue" text={story.segment.hook.dialogue}/>
+ <wording:Set name="action" text={hook-action}/>
+ </wording:Render>
+ <wording:Render id="courses-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>
+ <wording:Set name="dialogue" text={story.segment.courses.dialogue}/>
+ <wording:Set name="action" text={courses-action}/>
+ </wording:Render>
+ <wording:Render id="youtube-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>
+ <wording:Set name="dialogue" text={story.segment.youtube.dialogue}/>
+ <wording:Set name="action" text={youtube-action}/>
+ </wording:Render>
+ <wording:Render id="twitter-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>
+ <wording:Set name="dialogue" text={story.segment.twitter.dialogue}/>
+ <wording:Set name="action" text={twitter-action}/>
+ </wording:Render>
+ <wording:Render id="rundown-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>
+ <wording:Set name="dialogue" text={story.segment.rundown.dialogue}/>
+ <wording:Set name="action" text={rundown-action}/>
+ </wording:Render>
+
+ <!-- Five continuous takes, all referencing the one accepted location image. -->
+ <seedance:ReferenceVideo id="hook-take" model="mini" prompt={hook-prompt} duration={hook-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">
+ <seedance:Reference image={speaker-scene.image}/>
+ </seedance:ReferenceVideo>
+ <seedance:ReferenceVideo id="courses-take" model="mini" prompt={courses-prompt} duration={courses-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">
+ <seedance:Reference image={speaker-scene.image}/>
+ </seedance:ReferenceVideo>
+ <seedance:ReferenceVideo id="youtube-take" model="mini" prompt={youtube-prompt} duration={youtube-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">
+ <seedance:Reference image={speaker-scene.image}/>
+ </seedance:ReferenceVideo>
+ <seedance:ReferenceVideo id="twitter-take" model="mini" prompt={twitter-prompt} duration={twitter-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">
+ <seedance:Reference image={speaker-scene.image}/>
+ </seedance:ReferenceVideo>
+ <seedance:ReferenceVideo id="rundown-take" model="mini" prompt={rundown-prompt} duration={rundown-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">
+ <seedance:Reference image={speaker-scene.image}/>
+ </seedance:ReferenceVideo>
+
+ <space:Canvas id="vertical" width="720" height="1280"/>
+ <space:Frame id="speech-frame" within={vertical} left="0%" top="0%" right="100%" bottom="100%"/>
+ <space:Frame id="board-frame" within={vertical} left="0%" top="0%" right="100%" bottom="100%"/>
+ <space:Frame id="product-frame" within={vertical} left="46%" top="18%" right="96%" bottom="82%"/>
+ <space:Frame id="thumb-frame" within={vertical} left="14%" top="30%" right="86%" bottom="74%"/>
+ <space:Extent id="product-extent" width="1080" height="1920"/>
+ <space:Extent id="thumb-extent" width="1920" height="1080"/>
+
+ <!-- Five ordered Takes become one continuous speech coordinate space. -->
+ <speech:Spine id="speech" frame-rate="30"
+ visual-frame={speech-frame} visual-appearance={studio.speech.visual} visual-z="0">
+ <speech:Take video={hook-take.video} segment={story.segment.hook}/>
+ <speech:Take video={courses-take.video} segment={story.segment.courses}/>
+ <speech:Take video={youtube-take.video} segment={story.segment.youtube}/>
+ <speech:Take video={twitter-take.video} segment={story.segment.twitter}/>
+ <speech:Take video={rundown-take.video} segment={story.segment.rundown}/>
+ </speech:Spine>
+
+ <!-- One measured evidence pass locates the complete authored Script. -->
+ <whisperx:Alignment id="timing" narrative={story} audio={speech.audio}/>
+
+ <!-- Captions: one program-wide system driven by the Script and the measured map. -->
+ <fonts:Stack id="caption-font" family="inter" weight="800" style="normal"/>
+ <caption-fine:Style id="primary-caption" recipe={studio.caption.primary} font={caption-font}/>
+ <caption:Program id="caption-program" display={story.caption} default={primary-caption}/>
+ <caption-ai:Planner id="caption-plan" display={story.caption} program={caption-program} model="gemini-2.5-flash"/>
+ <caption-fine:Track id="captions" display={story.caption} correspondence={story.caption.correspondence} map={timing.map}
+ space={speech.space} program={caption-program} plan={caption-plan.plan}/>
+
+ <!-- The lined-paper ranking board: one progressive system over its five appearances. -->
+ <fonts:Stack id="board-font" family="shadows-into-light" weight="400" style="normal"/>
+ <linerank:BoardStyle id="paper-style" recipe={studio.linerank.board} font={board-font}/>
+ <linerank:Board id="board" map={timing.map} space={speech.space} frame={board-frame}
+ during={story.selection.board} triggers={story.moment.reveal} terminal={story.moment.done}
+ style={paper-style} title="Top 5 Most Popular Ways to learn AI">
+ <linerank:BoardItem id="item-5" rank="5" label="Instagram"/>
+ <linerank:BoardItem id="item-4" rank="4" label="AI Courses"/>
+ <linerank:BoardItem id="item-3" rank="3" label="YouTube"/>
+ <linerank:BoardItem id="item-2" rank="2" label="Twitter/X"/>
+ <linerank:BoardItem id="item-1" rank="1" label="The Rundown"/>
+ </linerank:Board>
+
+ <!-- Two editorial inserts: the YouTube thumbnail and the product's mobile layout. -->
+ <media-track:Track id="product-broll" map={timing.map} space={speech.space} canvas={vertical}>
+ <media-track:Item image={product-ui.image} extent={product-extent} frame={product-frame}
+ during={story.selection.product} appearance={studio.media.product} motion={studio.motion.product}/>
+ </media-track:Track>
+
+ <media-track:Track id="thumb-broll" map={timing.map} space={speech.space} canvas={vertical}>
+ <media-track:Item image={thumb-image.image} extent={thumb-extent} frame={thumb-frame}
+ during={story.selection.thumb} appearance={studio.media.thumb} motion={studio.motion.thumb}/>
+ </media-track:Track>
+
+ <film:Film id="main" canvas={vertical} space={speech.space} appearance={studio.film.vertical}>
+ <film:Track source={speech.visual}/>
+ <film:Track source={speech.audioTrack}/>
+ <film:Track source={board.visual}/>
+ <film:Track source={product-broll.visual}/>
+ <film:Track source={thumb-broll.visual}/>
+ <film:Track source={captions.track}/>
+ </film:Film>
+
+ <render:Video id="final" composition={main.composition} space={speech.space}/>
+</svml>
diff --git a/examples/reference-reconstruction/packages/local-linerank/README.md b/examples/reference-reconstruction/packages/local-linerank/README.md
new file mode 100644
index 00000000..fd0845ca
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/README.md
@@ -0,0 +1,59 @@
+# `@hypit/local-linerank`
+
+A project-local author component that draws a full-screen lined/grid-paper ranking board whose
+labels type in one character at a time and which can finish with a hand-drawn circle around the top
+item. It owns the whole composition — the paper surface, the ruled grid, the title, the numbered
+rows, the typewriter reveal and the closing circle — as one self-contained `VisualTrack`.
+
+It exists because no installed package expresses the reference's notebook-paper ranking list
+(the `@hypit/ranking` variants draw rounded boards with icon tiles, not paper with typed labels).
+
+## Surfaces
+
+- `linerank:BoardStyle` — compiles one SVS Recipe and one exact font into the board's Style.
+ The Recipe accepts exactly the keys the package lists; every other key is refused by name.
+- `linerank:Board` — the board itself. It takes `map`, `space`, `frame`, a `during` Selection
+ (every occurrence is one board window), a `triggers` Moment (one occurrence per Item, in document
+ order), a `terminal` Moment, a `style`, a `title` expression, and one `BoardItem` child per item.
+
+```svml
+<import as="linerank" from="@hypit/local-linerank@1"/>
+
+<fonts:Stack id="board-font" family="shadows-into-light" weight="400" style="normal"/>
+<linerank:BoardStyle id="paper-style" recipe={studio.linerank.board} font={board-font}/>
+<linerank:Board id="board" map={timing.map} space={speech.space} frame={board-frame}
+ during={story.selection.board} triggers={story.moment.reveal} terminal={story.moment.done}
+ style={paper-style} title="Top 5 Most Popular Ways to learn AI">
+ <linerank:BoardItem id="item-5" rank="5" label="Instagram"/>
+ <linerank:BoardItem id="item-1" rank="1" label="The Rundown"/>
+</linerank:Board>
+```
+
+The board reveals Items in document order; each label types into the row named by its `rank`
+(1 is the top row). Every label already revealed stays in later windows. The `terminal` Moment draws
+the hand-drawn circle around the top row.
+
+## Timing model
+
+- `during` may be a non-contiguous Selection; the number of occurrences must equal the number of
+ Items, and each occurrence becomes one board window.
+- Each Item's `trigger` Moment must fall inside its own window.
+- The typewriter reveal animates a `clip-path` inset over `label-length × type-frames-per-char`
+ frames, so the label reads in left-to-right one character at a time.
+- The circle scales in with a wobbly border-radius over `circle-frames` starting at the terminal
+ Moment.
+
+## Package layout
+
+```
+src/manifest.ts module identity, nominal Types, Producers, Surface vocabulary
+src/types.ts TypeScript shapes
+src/schedule.ts assert/seal functions and the schedule builder
+src/style.ts SVS Recipe decoder
+src/render.ts Program → VisualTrack renderer
+src/surface.ts markup decoders
+src/fragment.ts graph fragment wiring
+src/component.ts producer handlers and validators
+src/activation.ts activation contribution
+preview/Board.png preview image for the Board Surface
+```
diff --git a/examples/reference-reconstruction/packages/local-linerank/package.json b/examples/reference-reconstruction/packages/local-linerank/package.json
new file mode 100644
index 00000000..fd6583e1
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@hypit/local-linerank",
+ "version": "0.0.0-dev",
+ "license": "SEE LICENSE IN LICENSE",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "hypit": {
+ "activation": "./src/activation.ts"
+ },
+ "dependencies": {
+ "@hypit/artifact": "workspace:*",
+ "@hypit/component-kit": "workspace:*",
+ "@hypit/composition": "workspace:*",
+ "@hypit/elaborator": "workspace:*",
+ "@hypit/media": "workspace:*",
+ "@hypit/narrative": "workspace:*",
+ "@hypit/program-space": "workspace:*",
+ "@hypit/protocol": "workspace:*",
+ "@hypit/semantic-map": "workspace:*",
+ "@hypit/spatial": "workspace:*",
+ "@hypit/svs": "workspace:*",
+ "@hypit/temporal": "workspace:*",
+ "@hypit/text": "workspace:*",
+ "@hypit/markup": "workspace:*"
+ },
+ "devDependencies": {
+ "@hypit/core": "workspace:*"
+ }
+}
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/activation.ts b/examples/reference-reconstruction/packages/local-linerank/src/activation.ts
new file mode 100644
index 00000000..49febfff
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/activation.ts
@@ -0,0 +1,30 @@
+import { createMarkupSurfaceHostFacet } from "@hypit/markup";
+
+import {
+ decodeLinerankBoardSurface,
+ decodeLinerankStyleSurface,
+ linerankComponent,
+ linerankManifest,
+ linerankMarkupSurfaces,
+ linerankModuleRef,
+} from "./index.js";
+
+const facets = [
+ ["linerank-style", decodeLinerankStyleSurface],
+ ["linerank", decodeLinerankBoardSurface],
+] as const;
+
+export const hypitPackage = {
+ format: "hypit.node-package@1" as const,
+ modules: [{
+ manifest: linerankManifest,
+ }],
+ components: [linerankComponent],
+ hostFacets: facets.map(([surface, handler]) => createMarkupSurfaceHostFacet({
+ module: linerankModuleRef,
+ declaration: linerankMarkupSurfaces.find((item) => item.name === surface)!,
+ handler,
+ })),
+};
+
+export default hypitPackage;
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/component.ts b/examples/reference-reconstruction/packages/local-linerank/src/component.ts
new file mode 100644
index 00000000..54d260e3
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/component.ts
@@ -0,0 +1,110 @@
+import type { ComponentPackage, ProducerHandlerContext } from "@hypit/component-kit";
+import type { NarrativeMomentRef, NarrativeSelectionRef } from "@hypit/narrative";
+import type { ProgramSpace } from "@hypit/program-space";
+import { canonicalize } from "@hypit/protocol";
+import type { StoredValue } from "@hypit/protocol";
+import type { CompleteSemanticMap } from "@hypit/semantic-map";
+import type { SpatialFrame } from "@hypit/spatial";
+import type { Text } from "@hypit/text";
+
+import { linerankProducers, linerankTypes } from "./manifest.js";
+import {
+ appendLinerankItem,
+ appendLinerankItemSpec,
+ assertLinerankItemSpec,
+ assertLinerankProgram,
+ assertLinerankSchedule,
+ buildLinerankProgram,
+ buildLinerankSchedule,
+ createLinerankItemSet,
+ createLinerankItemSpecSet,
+ materializeLinerankTextItem,
+} from "./schedule.js";
+import { renderLinerankBoard } from "./render.js";
+import type {
+ LinerankHeader,
+ LinerankItemSet,
+ LinerankItemSpec,
+ LinerankItemSpecSet,
+ LinerankProgram,
+ LinerankSchedule,
+ LinerankStyle,
+ LinerankTextItemShell,
+} from "./types.js";
+
+function inline<T>(value: StoredValue | undefined, label: string): T {
+ if (value?.kind !== "inline") throw new Error(`${label} must be inline.`);
+ return value.value as unknown as T;
+}
+
+const output = (value: unknown) => ({ kind: "inline" as const, value: canonicalize(value) });
+
+export const linerankComponent: ComponentPackage = {
+ producers: [
+ {
+ producer: linerankProducers.materializeTextItem,
+ handler: ({ inputs }) => ({ outputs: { spec: output(materializeLinerankTextItem(
+ inline<LinerankTextItemShell>(inputs.shell?.value, "LinerankTextItemShell"),
+ inline<Text>(inputs.content?.value, "Text"),
+ )) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.createSpecs,
+ handler: () => ({ outputs: { set: output(createLinerankItemSpecSet()) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.appendSpec,
+ handler: ({ inputs }) => ({ outputs: { set: output(appendLinerankItemSpec(
+ inline<LinerankItemSpecSet>(inputs.set?.value, "LinerankItemSpecSet"),
+ inline<LinerankItemSpec>(inputs.spec?.value, "LinerankItemSpec"),
+ )) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.schedule,
+ handler: ({ inputs }) => ({ outputs: { schedule: output(buildLinerankSchedule({
+ header: inline<LinerankHeader>(inputs.header?.value, "LinerankHeader"),
+ items: inline<LinerankItemSpecSet>(inputs.items?.value, "LinerankItemSpecSet"),
+ map: inline<CompleteSemanticMap>(inputs.map?.value, "CompleteSemanticMap"),
+ space: inline<ProgramSpace>(inputs.space?.value, "ProgramSpace"),
+ outer: inline<NarrativeSelectionRef>(inputs.outer?.value, "NarrativeSelectionRef"),
+ triggers: inline<NarrativeMomentRef>(inputs.triggers?.value, "NarrativeMomentRef"),
+ terminal: inline<NarrativeMomentRef>(inputs.terminal?.value, "NarrativeMomentRef"),
+ })) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.createItems,
+ handler: () => ({ outputs: { set: output(createLinerankItemSet()) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.appendItem,
+ handler: ({ inputs }) => ({ outputs: { set: output(appendLinerankItem(
+ inline<LinerankItemSet>(inputs.set?.value, "LinerankItemSet"),
+ inline<LinerankItemSpec>(inputs.spec?.value, "LinerankItemSpec"),
+ )) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.program,
+ handler: ({ inputs }) => ({ outputs: { program: output(buildLinerankProgram(
+ inline<LinerankHeader>(inputs.header?.value, "LinerankHeader"),
+ inline<SpatialFrame>(inputs.frame?.value, "SpatialFrame"),
+ inline<LinerankSchedule>(inputs.schedule?.value, "LinerankSchedule"),
+ inline<LinerankStyle>(inputs.style?.value, "LinerankStyle"),
+ inline<Text>(inputs.title?.value, "Text").value,
+ inline<LinerankItemSet>(inputs.set?.value, "LinerankItemSet"),
+ )) }, needs: {} }),
+ },
+ {
+ producer: linerankProducers.render,
+ handler: ({ inputs }: ProducerHandlerContext) => ({ outputs: { track: output(renderLinerankBoard(
+ inline<ProgramSpace>(inputs.space?.value, "ProgramSpace"),
+ inline<LinerankProgram>(inputs.program?.value, "LinerankProgram"),
+ )) }, needs: {} }),
+ },
+ ],
+ validators: [
+ { type: linerankTypes.schedule,
+ handler: ({ value }) => assertLinerankSchedule(inline<LinerankSchedule>(value, "LinerankSchedule")) },
+ { type: linerankTypes.program,
+ handler: ({ value }) => assertLinerankProgram(inline<LinerankProgram>(value, "LinerankProgram")) },
+ ],
+};
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/fragment.ts b/examples/reference-reconstruction/packages/local-linerank/src/fragment.ts
new file mode 100644
index 00000000..6a34f844
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/fragment.ts
@@ -0,0 +1,103 @@
+import { compositionTypes } from "@hypit/composition";
+import { sealGraphFragment } from "@hypit/elaborator";
+import type { FragmentOperation, GraphFragment } from "@hypit/elaborator";
+import { narrativeTypes } from "@hypit/narrative";
+import { programSpaceTypes } from "@hypit/program-space";
+import { semanticMapTypes } from "@hypit/semantic-map";
+import { spatialTypes } from "@hypit/spatial";
+import { textTypes } from "@hypit/text";
+
+import { linerankProducers, linerankTypes } from "./manifest.js";
+
+const input = (name: string) => ({ kind: "fragment-input" as const, name });
+const operation = (id: string) => ({ kind: "fragment-operation" as const, operation: id });
+
+export type LinerankFragmentItem = {
+ readonly suffix: string;
+ readonly specName: string;
+ readonly contentName?: string;
+};
+
+export function createLinerankFragment(items: readonly LinerankFragmentItem[]) {
+ if (items.length === 0) throw new Error("Linerank Fragment requires at least one Item.");
+ const inputs: Array<GraphFragment["inputs"][number]> = [
+ { name: "header", type: linerankTypes.header },
+ { name: "map", type: semanticMapTypes.complete },
+ { name: "space", type: programSpaceTypes.programSpace },
+ { name: "outer", type: narrativeTypes.selection },
+ { name: "triggers", type: narrativeTypes.moment },
+ { name: "terminal", type: narrativeTypes.moment },
+ { name: "frame", type: spatialTypes.frame },
+ { name: "style", type: linerankTypes.style },
+ { name: "title", type: textTypes.text },
+ ];
+ const operations: FragmentOperation[] = [
+ { id: "specs", producer: linerankProducers.createSpecs, inputs: {}, result: { kind: "output", name: "set" } },
+ { id: "resolved", producer: linerankProducers.createItems, inputs: {}, result: { kind: "output", name: "set" } },
+ ];
+ let specs = operation("specs");
+ let resolved = operation("resolved");
+ for (const item of items) {
+ inputs.push({ name: item.specName, type: item.contentName === undefined ? linerankTypes.itemSpec : linerankTypes.textItemShell });
+ if (item.contentName !== undefined) inputs.push({ name: item.contentName, type: textTypes.text });
+ const resolvedSpec = item.contentName === undefined ? input(item.specName) : (() => {
+ const id = `materialize-${item.suffix}`;
+ operations.push({
+ id,
+ producer: linerankProducers.materializeTextItem,
+ inputs: { shell: input(item.specName), content: input(item.contentName!) },
+ result: { kind: "output", name: "spec" },
+ });
+ return operation(id);
+ })();
+ const semanticId = `spec-${item.suffix}`;
+ operations.push({
+ id: semanticId,
+ producer: linerankProducers.appendSpec,
+ inputs: { set: specs, spec: resolvedSpec },
+ result: { kind: "output", name: "set" },
+ });
+ specs = operation(semanticId);
+ const visualId = `item-${item.suffix}`;
+ operations.push({
+ id: visualId,
+ producer: linerankProducers.appendItem,
+ inputs: { set: resolved, spec: resolvedSpec },
+ result: { kind: "output", name: "set" },
+ });
+ resolved = operation(visualId);
+ }
+ operations.push({
+ id: "schedule",
+ producer: linerankProducers.schedule,
+ inputs: {
+ header: input("header"), items: specs, map: input("map"), space: input("space"),
+ outer: input("outer"), triggers: input("triggers"), terminal: input("terminal"),
+ },
+ result: { kind: "output", name: "schedule" },
+ });
+ operations.push({
+ id: "program",
+ producer: linerankProducers.program,
+ inputs: {
+ header: input("header"), frame: input("frame"), schedule: operation("schedule"),
+ style: input("style"), title: input("title"), set: resolved,
+ },
+ result: { kind: "output", name: "program" },
+ });
+ operations.push({
+ id: "visual",
+ producer: linerankProducers.render,
+ inputs: { space: input("space"), program: operation("program") },
+ result: { kind: "output", name: "track" },
+ });
+ return sealGraphFragment({
+ inputs,
+ operations,
+ exports: [
+ { name: "schedule", type: linerankTypes.schedule, root: operation("schedule") },
+ { name: "program", type: linerankTypes.program, root: operation("program") },
+ { name: "visual", type: compositionTypes.visualTrack, root: operation("visual") },
+ ],
+ });
+}
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/index.ts b/examples/reference-reconstruction/packages/local-linerank/src/index.ts
new file mode 100644
index 00000000..3f1ee038
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/index.ts
@@ -0,0 +1,41 @@
+export {
+ appendLinerankItem,
+ appendLinerankItemSpec,
+ assertLinerankItemSpec,
+ assertLinerankItemSpecSet,
+ assertLinerankProgram,
+ assertLinerankSchedule,
+ assertLinerankStyle,
+ assertLinerankTextItemShell,
+ buildLinerankProgram,
+ buildLinerankSchedule,
+ createLinerankItemSet,
+ createLinerankItemSpecSet,
+ materializeLinerankTextItem,
+ sealLinerankHeader,
+ sealLinerankTextItemShell,
+} from "./schedule.js";
+export { decodeLinerankStyle } from "./style.js";
+export { renderLinerankBoard } from "./render.js";
+export { linerankComponent } from "./component.js";
+export { createLinerankFragment } from "./fragment.js";
+export type { LinerankFragmentItem } from "./fragment.js";
+export {
+ linerankDependency,
+ linerankHeaderSchema,
+ linerankItemSpecSchema,
+ linerankTextItemShellSchema,
+ linerankItemSpecSetSchema,
+ linerankManifest,
+ linerankMarkupSurfaces,
+ linerankModuleRef,
+ linerankProducers,
+ linerankScheduleSchema,
+ linerankStyleSchema,
+ linerankTypes,
+} from "./manifest.js";
+export {
+ decodeLinerankBoardSurface,
+ decodeLinerankStyleSurface,
+} from "./surface.js";
+export type * from "./types.js";
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/manifest.ts b/examples/reference-reconstruction/packages/local-linerank/src/manifest.ts
new file mode 100644
index 00000000..77294d80
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/manifest.ts
@@ -0,0 +1,217 @@
+import { readFile } from "node:fs/promises";
+
+import { compositionDependency, compositionTypes } from "@hypit/composition";
+import { mediaDependency, mediaTypes } from "@hypit/media";
+import { narrativeDependency, narrativeTypes } from "@hypit/narrative";
+import { programSpaceDependency, programSpaceTypes } from "@hypit/program-space";
+import type { ModuleManifest, ProducerRef, TypeRef, ValueSchema } from "@hypit/protocol";
+import { semanticMapDependency, semanticMapTypes } from "@hypit/semantic-map";
+import { spatialDependency, spatialFrameSchema, spatialTypes } from "@hypit/spatial";
+import { svsRecipeType } from "@hypit/svs";
+import { temporalDependency } from "@hypit/temporal";
+import { textDependency, textTypes } from "@hypit/text";
+
+const previewImage = (file: string) => ({
+ mediaType: "image/png",
+ path: `preview/${file}`,
+ open: async () => Uint8Array.from(await readFile(new URL(`../preview/${file}`, import.meta.url))),
+});
+
+export const linerankModuleRef = { name: "@hypit/local-linerank", version: "1" } as const;
+export const linerankTypes = {
+ header: { module: linerankModuleRef, name: "LinerankHeader" },
+ itemSpec: { module: linerankModuleRef, name: "LinerankItemSpec" },
+ textItemShell: { module: linerankModuleRef, name: "LinerankTextItemShell" },
+ itemSpecs: { module: linerankModuleRef, name: "LinerankItemSpecSet" },
+ schedule: { module: linerankModuleRef, name: "LinerankSchedule" },
+ style: { module: linerankModuleRef, name: "LinerankStyle" },
+ items: { module: linerankModuleRef, name: "LinerankItemSet" },
+ program: { module: linerankModuleRef, name: "LinerankProgram" },
+} satisfies Record<string, TypeRef>;
+
+export const linerankProducers = {
+ materializeTextItem: { module: linerankModuleRef, name: "materialize-linerank-text-item" },
+ createSpecs: { module: linerankModuleRef, name: "create-linerank-item-specs" },
+ appendSpec: { module: linerankModuleRef, name: "append-linerank-item-spec" },
+ schedule: { module: linerankModuleRef, name: "build-linerank-schedule" },
+ createItems: { module: linerankModuleRef, name: "create-linerank-items" },
+ appendItem: { module: linerankModuleRef, name: "append-linerank-item" },
+ program: { module: linerankModuleRef, name: "build-linerank-program" },
+ render: { module: linerankModuleRef, name: "render-linerank-board" },
+} satisfies Record<string, ProducerRef>;
+
+const string = { kind: "string", minLength: 1 } as const;
+const integer = { kind: "number", integer: true } as const;
+const unsigned = { kind: "number", integer: true, minimum: 0 } as const;
+const object = (fields: Readonly<Record<string, { readonly schema: ValueSchema; readonly optional?: boolean }>>, allowUnknown = false): ValueSchema => ({
+ kind: "object", fields, ...(allowUnknown ? { allowUnknown: true } : {}),
+});
+
+export const linerankHeaderSchema: ValueSchema = object({ id: { schema: string } });
+export const linerankItemSpecSchema: ValueSchema = object({
+ id: { schema: string }, rank: { schema: integer }, label: { schema: string },
+});
+export const linerankTextItemShellSchema: ValueSchema = object({
+ id: { schema: string }, rank: { schema: integer },
+});
+export const linerankItemSpecSetSchema: ValueSchema = object({
+ items: { schema: { kind: "array", items: linerankItemSpecSchema } },
+});
+const frameSpan = object({ startFrame: { schema: unsigned }, endFrameExclusive: { schema: unsigned } });
+export const linerankScheduleSchema: ValueSchema = object({
+ id: { schema: string },
+ windows: { schema: { kind: "array", minItems: 1, items: frameSpan } },
+ terminalFrame: { schema: unsigned },
+ entries: { schema: { kind: "array", minItems: 1, items: object({
+ itemId: { schema: string }, rank: { schema: integer }, triggerFrame: { schema: unsigned },
+ }) } },
+});
+export const linerankStyleSchema: ValueSchema = object({}, true);
+export const linerankItemSetSchema: ValueSchema = object({
+ items: { schema: { kind: "array", items: linerankItemSpecSchema } },
+});
+export const linerankProgramSchema: ValueSchema = object({
+ id: { schema: string },
+ frame: { schema: spatialFrameSchema },
+ schedule: { schema: linerankScheduleSchema },
+ style: { schema: object({}, true) },
+ title: { schema: string },
+ items: { schema: { kind: "array", minItems: 1, items: linerankItemSpecSchema } },
+}, true);
+
+export const linerankMarkupSurfaces = [
+ {
+ name: "linerank-style", tag: "BoardStyle", mode: "structured", outputs: [linerankTypes.style],
+ vocabulary: {
+ summary: "Compiles one SVS Recipe and one exact font into the Style a lined-paper ranking Board is drawn in.",
+ attributes: [
+ { name: "id", kind: "identifier", required: true, summary: "Names this Style so a Board can reference it." },
+ { name: "recipe", kind: "reference", required: true, accepts: [svsRecipeType], summary: "Chooses the Recipe carrying the paper, ruled lines, title, numbers, label typography, typewriter rhythm and circle geometry.",
+ recipe: [
+ { name: "paper-background", required: false, fallback: "#ffffff", summary: "Sets the paper's fill color." },
+ { name: "rule-color", required: false, fallback: "#cfe0f5", summary: "Sets the color of the graph-paper ruled lines." },
+ { name: "rule-gap", required: false, fallback: "64", summary: "Sets the gap in pixels between ruled lines, horizontally and vertically." },
+ { name: "title-size", required: false, fallback: "40", summary: "Sets the size in pixels the title is set at." },
+ { name: "title-weight", required: false, fallback: "700", summary: "Sets the weight the title is set at." },
+ { name: "title-color", required: false, fallback: "#111111", summary: "Sets the color the title is drawn in." },
+ { name: "title-line-height", required: false, fallback: "1.15", summary: "Sets the line height the title is set on." },
+ { name: "number-size", required: false, fallback: "34", summary: "Sets the size in pixels the row numbers are set at." },
+ { name: "number-weight", required: false, fallback: "600", summary: "Sets the weight the row numbers are set at." },
+ { name: "number-color", required: false, fallback: "#222222", summary: "Sets the color the row numbers are drawn in." },
+ { name: "label-size", required: false, fallback: "36", summary: "Sets the size in pixels each list label is set at." },
+ { name: "label-weight", required: false, fallback: "500", summary: "Sets the weight each list label is set at." },
+ { name: "label-color", required: false, fallback: "#111111", summary: "Sets the color each list label is drawn in." },
+ { name: "label-line-height", required: false, fallback: "1.2", summary: "Sets the line height each list label is set on." },
+ { name: "top-padding", required: false, fallback: "120", summary: "Sets the gap in pixels between the title and the first row." },
+ { name: "left-padding", required: false, fallback: "56", summary: "Sets the left inset in pixels of the numbered rows." },
+ { name: "right-padding", required: false, fallback: "40", summary: "Sets the right inset in pixels of the label area." },
+ { name: "row-height", required: false, fallback: "72", summary: "Sets the height in pixels of one list row." },
+ { name: "row-gap", required: false, fallback: "10", summary: "Sets the gap in pixels between list rows." },
+ { name: "number-width", required: false, fallback: "64", summary: "Sets the width in pixels of the number column." },
+ { name: "type-frames-per-char", required: false, fallback: "4", summary: "Sets how many frames each typed character takes to reveal." },
+ { name: "circle-color", required: false, fallback: "#111111", summary: "Sets the color of the hand-drawn circle around the top item." },
+ { name: "circle-width", required: false, fallback: "3", summary: "Sets the stroke width in pixels of the hand-drawn circle." },
+ { name: "circle-frames", required: false, fallback: "18", summary: "Sets how many frames the hand-drawn circle takes to draw in." },
+ { name: "board-stack", required: false, fallback: "20", summary: "Sets the draw order the paper board is placed at." },
+ { name: "row-stack", required: false, fallback: "30", summary: "Sets the draw order the title and rows are placed at." },
+ { name: "circle-stack", required: false, fallback: "40", summary: "Sets the draw order the hand-drawn circle is placed at." },
+ ] },
+ { name: "font", kind: "reference", required: true, accepts: [mediaTypes.fontArtifact, mediaTypes.fontStack], summary: "Chooses the exact face, or a whole stack that already carries its own fallbacks, the board copy is set in." },
+ ],
+ ports: [
+ { name: "", type: linerankTypes.style, summary: "The compiled visual Style, addressed by the element's own id." },
+ ],
+ example: `<linerank:BoardStyle id="paper-style" recipe={studio.linerank.board} font={ui-font}/>`,
+ notes: [
+ "The element is empty; it accepts no children and no text.",
+ "The Recipe accepts exactly the properties listed here; every other property is refused by name.",
+ ],
+ },
+ },
+ {
+ name: "linerank", tag: "Board", mode: "structured", outputs: [linerankTypes.header, linerankTypes.itemSpec, linerankTypes.textItemShell, textTypes.text, linerankTypes.schedule, linerankTypes.program, compositionTypes.visualTrack],
+ vocabulary: {
+ summary: "Draws a full-screen lined-paper ranking board that reveals one numbered item at a time as its label types in, settles, and can finish with a hand-drawn circle around the top item.",
+ appearance:
+ "A full-frame sheet of lined paper: a light fill with faint horizontal ruled lines and a vertical margin line. A title sits centered near the top. Below it, every rank row is already present as its number (1. 2. 3. …); the label of the item revealed on each board occurrence types in left-to-right, one character at a time, over the board window where it first appears, and every label already revealed stays where it landed in later windows. On the final window the top-ranked label is encircled by a thin oval line that draws in over the terminal stretch.",
+ preview: previewImage("Board.png"),
+ attributes: [
+ { name: "id", kind: "identifier", required: true, summary: "Names this board so its Schedule, Program and Tracks can be referenced elsewhere in the Source." },
+ { name: "map", kind: "reference", required: true, accepts: [semanticMapTypes.complete], summary: "Chooses the measured SemanticMap that gives every trigger its frame." },
+ { name: "space", kind: "reference", required: true, accepts: [programSpaceTypes.programSpace], summary: "Chooses the ProgramSpace the board is timed and rendered against." },
+ { name: "frame", kind: "reference", required: true, accepts: [spatialTypes.frame], summary: "Chooses the Frame the whole board occupies." },
+ { name: "during", kind: "reference", required: true, accepts: [narrativeTypes.selection], summary: "Chooses the Selection the board is on screen for; every occurrence becomes one board window." },
+ { name: "triggers", kind: "reference", required: true, accepts: [narrativeTypes.moment], summary: "Chooses the Moment whose occurrences reveal one BoardItem each, in document order." },
+ { name: "terminal", kind: "reference", required: true, accepts: [narrativeTypes.moment], summary: "Chooses the Moment the board settles on; the hand-drawn circle draws in there." },
+ { name: "style", kind: "reference", required: true, accepts: [linerankTypes.style], summary: "Chooses the BoardStyle this board is drawn in." },
+ { name: "title", kind: "expression", required: true, accepts: [textTypes.text], summary: "Sets the board's title copy, written literally or chosen from an existing Text." },
+ ],
+ children: [
+ { tag: "BoardItem", cardinality: "many",
+ summary: "One item of the board, placed at its own trigger occurrence in document order; it is empty.",
+ attributes: [
+ { name: "id", kind: "identifier", required: false, summary: "Names this Item within the board; an omitted id is generated from the Item's position." },
+ { name: "rank", kind: "literal", required: true, summary: "Chooses the numbered row (1 is the top row) this Item's label is typed into." },
+ { name: "label", kind: "expression", required: true, accepts: [textTypes.text], summary: "Sets the Item's label copy, written literally or chosen from an existing Text." },
+ ] },
+ ],
+ ports: [
+ { name: "schedule", type: linerankTypes.schedule, summary: "The resolved Schedule: each board window and each Item's trigger and typing span." },
+ { name: "program", type: linerankTypes.program, summary: "The resolved board: its Frame, Style, Schedule, title and ordered Items." },
+ { name: "visual", type: compositionTypes.visualTrack, summary: "The rendered board, an ordinary peer VisualTrack." },
+ ],
+ example: `<linerank:BoardStyle id="paper-style" recipe={studio.linerank.board} font={hand-font}/>
+<linerank:Board id="board" map={timing.map} space={speech.space} frame={board-frame}
+ during={story.selection.board} triggers={story.moment.reveal} terminal={story.moment.done}
+ style={paper-style} title="Top 5 Most Popular Ways to learn AI">
+ <linerank:BoardItem id="row-five" rank="5" label="Instagram"/>
+ <linerank:BoardItem id="row-one" rank="1" label="The Rundown"/>
+</linerank:Board>`,
+ notes: [
+ "The board requires at least one BoardItem, accepts no other child and no text of its own, and Item ids must be unique within it.",
+ "Ranks must be unique; the top row is rank 1.",
+ "`during` may be a non-contiguous Selection; each occurrence becomes one board window, and the number of windows must equal the number of Items.",
+ "The label of the Item revealed on window N types in during that window and stays visible in every later window.",
+ ],
+ },
+ },
+] as const;
+
+export const linerankManifest: ModuleManifest = {
+ format: "hypit.module@1", name: linerankModuleRef.name, version: linerankModuleRef.version,
+ dependencies: [mediaDependency, narrativeDependency, semanticMapDependency, programSpaceDependency, spatialDependency, temporalDependency, compositionDependency, textDependency],
+ types: [
+ { name: linerankTypes.header.name },
+ { name: linerankTypes.itemSpec.name },
+ { name: linerankTypes.textItemShell.name },
+ { name: linerankTypes.itemSpecs.name },
+ { name: linerankTypes.schedule.name },
+ { name: linerankTypes.style.name },
+ { name: linerankTypes.items.name },
+ { name: linerankTypes.program.name },
+ ],
+ capabilities: [],
+ producers: [
+ { name: linerankProducers.materializeTextItem.name, inputs: [{ name: "shell", type: linerankTypes.textItemShell }, { name: "content", type: textTypes.text }], outputs: [{ name: "spec", type: linerankTypes.itemSpec }], needs: [] },
+ { name: linerankProducers.createSpecs.name, inputs: [], outputs: [{ name: "set", type: linerankTypes.itemSpecs }], needs: [] },
+ { name: linerankProducers.appendSpec.name, inputs: [{ name: "set", type: linerankTypes.itemSpecs }, { name: "spec", type: linerankTypes.itemSpec }], outputs: [{ name: "set", type: linerankTypes.itemSpecs }], needs: [] },
+ { name: linerankProducers.schedule.name, inputs: [
+ { name: "header", type: linerankTypes.header }, { name: "items", type: linerankTypes.itemSpecs },
+ { name: "map", type: semanticMapTypes.complete }, { name: "space", type: programSpaceTypes.programSpace },
+ { name: "outer", type: narrativeTypes.selection }, { name: "triggers", type: narrativeTypes.moment },
+ { name: "terminal", type: narrativeTypes.moment },
+ ], outputs: [{ name: "schedule", type: linerankTypes.schedule }], needs: [] },
+ { name: linerankProducers.createItems.name, inputs: [], outputs: [{ name: "set", type: linerankTypes.items }], needs: [] },
+ { name: linerankProducers.appendItem.name, inputs: [{ name: "set", type: linerankTypes.items }, { name: "spec", type: linerankTypes.itemSpec }], outputs: [{ name: "set", type: linerankTypes.items }], needs: [] },
+ { name: linerankProducers.program.name, inputs: [
+ { name: "header", type: linerankTypes.header }, { name: "frame", type: spatialTypes.frame },
+ { name: "schedule", type: linerankTypes.schedule }, { name: "style", type: linerankTypes.style },
+ { name: "title", type: textTypes.text }, { name: "set", type: linerankTypes.items },
+ ], outputs: [{ name: "program", type: linerankTypes.program }], needs: [] },
+ { name: linerankProducers.render.name, inputs: [
+ { name: "space", type: programSpaceTypes.programSpace }, { name: "program", type: linerankTypes.program },
+ ], outputs: [{ name: "track", type: compositionTypes.visualTrack }], needs: [] },
+ ],
+};
+
+export const linerankDependency = { module: linerankModuleRef } as const;
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/render.ts b/examples/reference-reconstruction/packages/local-linerank/src/render.ts
new file mode 100644
index 00000000..3fbb1e5f
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/render.ts
@@ -0,0 +1,289 @@
+import {
+ assertVisualTrackIdentity,
+ sealVisualTrack,
+} from "@hypit/composition";
+import type {
+ VisualAnimation,
+ VisualElement,
+ VisualPresent,
+ VisualStyleDeclaration,
+ VisualTrack,
+} from "@hypit/composition";
+import { assertProgramSpaceIdentity } from "@hypit/program-space";
+import type { ProgramSpace } from "@hypit/program-space";
+
+import { assertLinerankProgram, assertLinerankSchedule } from "./schedule.js";
+import type { LinerankProgram, LinerankStyle, LinerankTextStyle } from "./types.js";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function px(value: number): string {
+ return `${Math.round(value * 1_000_000) / 1_000_000}px`;
+}
+
+function absoluteBox(input: {
+ readonly id: string;
+ readonly order: number;
+ readonly parent?: string;
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+ readonly style?: readonly VisualStyleDeclaration[];
+ readonly animation?: VisualAnimation;
+}): VisualElement {
+ return {
+ id: input.id,
+ ...(input.parent === undefined ? {} : { parent: input.parent }),
+ order: input.order,
+ kind: "box",
+ style: [
+ { name: "height", value: px(input.height) },
+ { name: "left", value: px(input.x) },
+ { name: "position", value: "absolute" },
+ { name: "top", value: px(input.y) },
+ { name: "width", value: px(input.width) },
+ ...(input.style ?? []),
+ ],
+ ...(input.animation === undefined ? {} : { animation: input.animation }),
+ };
+}
+
+function textStyle(value: LinerankTextStyle, align: "left" | "center", nowrap: boolean): VisualStyleDeclaration[] {
+ return [
+ { name: "align-items", value: "center" },
+ { name: "color", value: value.color },
+ { name: "display", value: "flex" },
+ { name: "font-size", value: px(value.sizePx) },
+ { name: "justify-content", value: align === "left" ? "start" : "center" },
+ { name: "line-height", value: value.lineHeight },
+ { name: "overflow", value: "hidden" },
+ { name: "text-align", value: align },
+ { name: "white-space", value: nowrap ? "nowrap" : "normal" },
+ ];
+}
+
+function simpleText(input: {
+ readonly id: string;
+ readonly order: number;
+ readonly parent?: string;
+ readonly text: string;
+ readonly typography: LinerankTextStyle;
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+ readonly align?: "left" | "center";
+ readonly nowrap?: boolean;
+ readonly style?: readonly VisualStyleDeclaration[];
+ readonly animation?: VisualAnimation;
+}): VisualElement {
+ return {
+ id: input.id,
+ ...(input.parent === undefined ? {} : { parent: input.parent }),
+ order: input.order,
+ kind: "text",
+ text: input.text,
+ fonts: structuredClone(input.typography.fonts),
+ style: [
+ { name: "height", value: px(input.height) },
+ { name: "left", value: px(input.x) },
+ { name: "position", value: "absolute" },
+ { name: "top", value: px(input.y) },
+ { name: "width", value: px(input.width) },
+ ...textStyle(input.typography, input.align ?? "left", input.nowrap ?? true),
+ ...(input.style ?? []),
+ ],
+ ...(input.animation === undefined ? {} : { animation: input.animation }),
+ };
+}
+
+function present(input: {
+ readonly id: string;
+ readonly start: number;
+ readonly end: number;
+ readonly stacking: number;
+ readonly tieBreak: string;
+ readonly elements: readonly VisualElement[];
+}): VisualPresent {
+ return {
+ id: input.id,
+ span: { startFrame: input.start, endFrameExclusive: input.end },
+ stacking: { order: input.stacking, tieBreak: input.tieBreak },
+ elements: input.elements,
+ };
+}
+
+function typewriterAnimation(
+ duration: number,
+ revealFrames: number,
+ fullWidth: number,
+): VisualAnimation {
+ const clipped = `inset(0px ${px(fullWidth)} 0px 0px)`;
+ const revealed = "inset(0px 0px 0px 0px)";
+ return {
+ keyframes: [
+ { atFrame: 0, style: [{ name: "clip-path", value: clipped }] },
+ { atFrame: Math.min(revealFrames, duration), style: [{ name: "clip-path", value: revealed }] },
+ ],
+ };
+}
+
+function circleAnimation(
+ offset: number,
+ circleFrames: number,
+ duration: number,
+): VisualAnimation {
+ const start = Math.min(offset, duration);
+ const end = Math.min(offset + circleFrames, duration);
+ const hidden = [
+ { name: "opacity", value: 0 },
+ { name: "transform", value: "translate(-50%,-50%) scale(0.72) rotate(-2deg)" },
+ ] as const;
+ return {
+ keyframes: [
+ { atFrame: 0, style: [...hidden] },
+ ...(start === 0 ? [] : [{ atFrame: start, style: [...hidden] }]),
+ { atFrame: Math.max(end, start + 1), style: [
+ { name: "opacity", value: 1 },
+ { name: "transform", value: "translate(-50%,-50%) scale(1) rotate(-2deg)" },
+ ] },
+ ],
+ };
+}
+
+function estimatedLabelWidth(label: string, style: LinerankStyle): number {
+ return Math.max(1, Math.round(label.length * style.label.sizePx * 0.62));
+}
+
+function rowY(program: LinerankProgram, rank: number): number {
+ const { frame, style } = program;
+ const index = rank - 1;
+ return frame.yPx + style.topPaddingPx + index * (style.rowHeightPx + style.rowGapPx);
+}
+
+function rowLabelWidth(program: LinerankProgram): number {
+ const { frame, style } = program;
+ return frame.widthPx - style.leftPaddingPx - style.numberWidthPx - style.rightPaddingPx;
+}
+
+export function renderLinerankBoard(space: ProgramSpace, program: LinerankProgram): VisualTrack {
+ assertProgramSpaceIdentity(space);
+ assertLinerankProgram(program);
+ assertLinerankSchedule(program.schedule);
+ const { frame, style, schedule, title, items } = program;
+ const maxRank = Math.max(...items.map((item) => item.rank));
+ const labelWidth = rowLabelWidth(program);
+ const presents: VisualPresent[] = [];
+
+ for (const [windowIndex, window] of schedule.windows.entries()) {
+ const boardElements: VisualElement[] = [];
+ // Paper surface.
+ boardElements.push(absoluteBox({
+ id: "paper", order: 0, x: frame.xPx, y: frame.yPx, width: frame.widthPx, height: frame.heightPx,
+ style: [
+ { name: "background", value: style.paperBackground },
+ { name: "box-sizing", value: "border-box" },
+ { name: "overflow", value: "hidden" },
+ ],
+ }));
+ // Graph-paper grid: faint horizontal and vertical ruled lines.
+ const lineCount = Math.floor(frame.heightPx / style.ruleGapPx);
+ for (let line = 1; line <= lineCount; line += 1) {
+ const y = frame.yPx + line * style.ruleGapPx;
+ if (y >= frame.yPx + frame.heightPx) break;
+ boardElements.push(absoluteBox({
+ id: `rule-h-${line}`, parent: "paper", order: boardElements.length,
+ x: 0, y, width: frame.widthPx, height: 1,
+ style: [{ name: "background", value: style.ruleColor }],
+ }));
+ }
+ const columnCount = Math.floor(frame.widthPx / style.ruleGapPx);
+ for (let column = 1; column <= columnCount; column += 1) {
+ const x = frame.xPx + column * style.ruleGapPx;
+ if (x >= frame.xPx + frame.widthPx) break;
+ boardElements.push(absoluteBox({
+ id: `rule-v-${column}`, parent: "paper", order: boardElements.length,
+ x, y: 0, width: 1, height: frame.heightPx,
+ style: [{ name: "background", value: style.ruleColor }],
+ }));
+ }
+ // Title, centered near the top.
+ boardElements.push(simpleText({
+ id: "title", parent: "paper", order: boardElements.length,
+ text: title, typography: style.title,
+ x: style.leftPaddingPx, y: 36, width: frame.widthPx - style.leftPaddingPx - style.rightPaddingPx,
+ height: style.title.sizePx * style.title.lineHeight * 2,
+ align: "center",
+ nowrap: false,
+ }));
+ // Empty numbered rows for every rank.
+ for (let rank = 1; rank <= maxRank; rank += 1) {
+ const y = rowY(program, rank);
+ boardElements.push(simpleText({
+ id: `number-${rank}`, parent: "paper", order: boardElements.length,
+ text: `${rank}.`, typography: style.number,
+ x: style.leftPaddingPx, y, width: style.numberWidthPx, height: style.rowHeightPx,
+ align: "left",
+ }));
+ }
+ // Revealed labels.
+ for (let index = 0; index <= windowIndex && index < items.length; index += 1) {
+ const item = items[index]!;
+ const width = Math.min(estimatedLabelWidth(item.label, style), labelWidth);
+ const y = rowY(program, item.rank);
+ const firstReveal = index === windowIndex;
+ const typingFrames = Math.max(1, Math.round(item.label.length * style.typeFramesPerChar));
+ boardElements.push(simpleText({
+ id: `label-${item.id}`, parent: "paper", order: boardElements.length,
+ text: item.label, typography: style.label,
+ x: style.leftPaddingPx + style.numberWidthPx, y,
+ width: firstReveal ? width : labelWidth,
+ height: style.rowHeightPx,
+ align: "left",
+ ...(firstReveal ? {
+ animation: typewriterAnimation(window.endFrameExclusive - window.startFrame, typingFrames, width),
+ } : {}),
+ }));
+ }
+ presents.push(present({
+ id: `${program.id}:board:${windowIndex}`,
+ start: window.startFrame,
+ end: window.endFrameExclusive,
+ stacking: style.boardStackingOrder,
+ tieBreak: `${program.id}:${String(windowIndex).padStart(4, "0")}:board`,
+ elements: boardElements,
+ }));
+ // Hand-drawn circle around rank 1 in the final window.
+ if (windowIndex === schedule.windows.length - 1) {
+ const circleWidth = labelWidth;
+ const circleX = style.leftPaddingPx + style.numberWidthPx + circleWidth / 2;
+ const circleY = rowY(program, 1) + style.rowHeightPx / 2;
+ const offset = schedule.terminalFrame - window.startFrame;
+ presents.push(present({
+ id: `${program.id}:circle`,
+ start: window.startFrame,
+ end: window.endFrameExclusive,
+ stacking: style.circleStackingOrder,
+ tieBreak: `${program.id}:${String(windowIndex).padStart(4, "0")}:circle`,
+ elements: [absoluteBox({
+ id: "circle", order: 0,
+ x: circleX, y: circleY, width: circleWidth, height: style.rowHeightPx * 1.35,
+ style: [
+ { name: "border", value: `${px(style.circleWidthPx)} solid ${style.circleColor}` },
+ { name: "border-radius", value: "50% / 55% 45% 60% 40%" },
+ { name: "box-sizing", value: "border-box" },
+ { name: "transform", value: "translate(-50%,-50%) scale(0.72) rotate(-2deg)" },
+ ],
+ animation: circleAnimation(offset, style.circleFrames, window.endFrameExclusive - window.startFrame),
+ })],
+ }));
+ }
+ }
+
+ const track = sealVisualTrack({ visualIr: "hypit.visual-ir@1", id: program.id, presents });
+ assertVisualTrackIdentity(track, space);
+ return track;
+}
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/schedule.ts b/examples/reference-reconstruction/packages/local-linerank/src/schedule.ts
new file mode 100644
index 00000000..3283e06e
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/schedule.ts
@@ -0,0 +1,293 @@
+import type { SynchronizedMedia } from "@hypit/media";
+import type { NarrativeMomentRef, NarrativeSelectionRef } from "@hypit/narrative";
+import { assertProgramSpaceIdentity, programSpaceFrameCount } from "@hypit/program-space";
+import type { ProgramSpace } from "@hypit/program-space";
+import { canonicalize } from "@hypit/protocol";
+import type { CompleteSemanticMap } from "@hypit/semantic-map";
+import { assertSpatialFrame } from "@hypit/spatial";
+import { locateMomentOccurrences, locateSelectionOccurrences } from "@hypit/temporal";
+
+import type {
+ LinerankHeader,
+ LinerankItemSet,
+ LinerankItemSpec,
+ LinerankItemSpecSet,
+ LinerankProgram,
+ LinerankSchedule,
+ LinerankStyle,
+ LinerankTextItemShell,
+} from "./types.js";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function identity(value: string, label: string): void {
+ assert(/^[A-Za-z][A-Za-z0-9_.:#-]{0,191}$/u.test(value), `${label} is invalid.`);
+}
+
+function frame(value: number, label: string): void {
+ assert(Number.isSafeInteger(value) && value >= 0, `${label} must be a non-negative frame.`);
+}
+
+function finite(value: number, label: string): void {
+ assert(Number.isFinite(value), `${label} must be finite.`);
+}
+
+function nonNegative(value: number, label: string): void {
+ finite(value, label);
+ assert(value >= 0, `${label} must be non-negative.`);
+}
+
+function positive(value: number, label: string): void {
+ finite(value, label);
+ assert(value > 0, `${label} must be positive.`);
+}
+
+function integer(value: number, label: string, minimum = 0): void {
+ assert(Number.isSafeInteger(value) && value >= minimum, `${label} must be an integer >= ${minimum}.`);
+}
+
+function stacking(value: number, label: string): void {
+ assert(Number.isSafeInteger(value), `${label} must be an integer.`);
+}
+
+function color(value: string, label: string): void {
+ assert(value === "transparent" || /^#[0-9a-f]{3,8}$/iu.test(value), `${label} must be a hexadecimal color or transparent.`);
+}
+
+export function assertLinerankTextStyle(value: LinerankStyle["title"], label: string): void {
+ assert(value.fonts.length > 0, `${label}.fonts is empty.`);
+ positive(value.sizePx, `${label}.sizePx`);
+ integer(value.weight, `${label}.weight`, 1);
+ assert(value.weight <= 1_000, `${label}.weight exceeds 1000.`);
+ color(value.color, `${label}.color`);
+ positive(value.lineHeight, `${label}.lineHeight`);
+}
+
+export function assertLinerankStyle(value: LinerankStyle): void {
+ color(value.paperBackground, "LinerankStyle.paperBackground");
+ color(value.ruleColor, "LinerankStyle.ruleColor");
+ positive(value.ruleGapPx, "LinerankStyle.ruleGapPx");
+ assertLinerankTextStyle(value.title, "LinerankStyle.title");
+ assertLinerankTextStyle(value.number, "LinerankStyle.number");
+ assertLinerankTextStyle(value.label, "LinerankStyle.label");
+ nonNegative(value.topPaddingPx, "LinerankStyle.topPaddingPx");
+ nonNegative(value.leftPaddingPx, "LinerankStyle.leftPaddingPx");
+ nonNegative(value.rightPaddingPx, "LinerankStyle.rightPaddingPx");
+ positive(value.rowHeightPx, "LinerankStyle.rowHeightPx");
+ nonNegative(value.rowGapPx, "LinerankStyle.rowGapPx");
+ nonNegative(value.numberWidthPx, "LinerankStyle.numberWidthPx");
+ integer(value.typeFramesPerChar, "LinerankStyle.typeFramesPerChar", 1);
+ color(value.circleColor, "LinerankStyle.circleColor");
+ nonNegative(value.circleWidthPx, "LinerankStyle.circleWidthPx");
+ integer(value.circleFrames, "LinerankStyle.circleFrames", 1);
+ stacking(value.boardStackingOrder, "LinerankStyle.boardStackingOrder");
+ stacking(value.rowStackingOrder, "LinerankStyle.rowStackingOrder");
+ stacking(value.circleStackingOrder, "LinerankStyle.circleStackingOrder");
+}
+
+export function assertLinerankHeader(value: LinerankHeader): void {
+ identity(value.id, "LinerankHeader.id");
+}
+
+export function sealLinerankHeader(value: LinerankHeader): LinerankHeader {
+ assertLinerankHeader(value);
+ return canonicalize(value) as unknown as LinerankHeader;
+}
+
+export function assertLinerankItemSpec(value: LinerankItemSpec): void {
+ identity(value.id, "LinerankItemSpec.id");
+ integer(value.rank, `LinerankItemSpec.${value.id}.rank`, 1);
+ assert(value.label.trim().length > 0, `LinerankItemSpec.${value.id}.label is empty.`);
+}
+
+export function assertLinerankTextItemShell(value: LinerankTextItemShell): void {
+ identity(value.id, "LinerankTextItemShell.id");
+ integer(value.rank, `LinerankTextItemShell.${value.id}.rank`, 1);
+}
+
+export function sealLinerankTextItemShell(value: LinerankTextItemShell): LinerankTextItemShell {
+ const result = canonicalize(value) as unknown as LinerankTextItemShell;
+ assertLinerankTextItemShell(result);
+ return result;
+}
+
+export function materializeLinerankTextItem(shell: LinerankTextItemShell, content: import("@hypit/text").Text): LinerankItemSpec {
+ assertLinerankTextItemShell(shell);
+ if (content.value.trim().length === 0) throw new Error(`Linerank Text Item ${shell.id} content is empty.`);
+ const result: LinerankItemSpec = { ...shell, label: content.value.trim() };
+ assertLinerankItemSpec(result);
+ return canonicalize(result) as unknown as LinerankItemSpec;
+}
+
+export function createLinerankItemSpecSet(): LinerankItemSpecSet {
+ return { items: [] };
+}
+
+export function assertLinerankItemSpecSet(value: LinerankItemSpecSet): void {
+ assert(Array.isArray(value.items), "LinerankItemSpecSet is invalid.");
+ const ids = new Set<string>();
+ const ranks = new Set<number>();
+ for (const item of value.items) {
+ assertLinerankItemSpec(item);
+ assert(!ids.has(item.id), `LinerankItemSpecSet repeats ${item.id}.`);
+ ids.add(item.id);
+ assert(!ranks.has(item.rank), `LinerankItemSpecSet repeats rank ${item.rank}.`);
+ ranks.add(item.rank);
+ }
+}
+
+export function appendLinerankItemSpec(set: LinerankItemSpecSet, spec: LinerankItemSpec): LinerankItemSpecSet {
+ assertLinerankItemSpecSet(set);
+ assertLinerankItemSpec(spec);
+ assert(!set.items.some((item) => item.id === spec.id), `Linerank Item ${spec.id} is duplicated.`);
+ assert(!set.items.some((item) => item.rank === spec.rank), `Linerank Item rank ${spec.rank} is duplicated.`);
+ const result: LinerankItemSpecSet = { items: [...set.items, structuredClone(spec)] };
+ assertLinerankItemSpecSet(result);
+ return canonicalize(result) as unknown as LinerankItemSpecSet;
+}
+
+export function buildLinerankSchedule(input: {
+ readonly header: LinerankHeader;
+ readonly items: LinerankItemSpecSet;
+ readonly map: CompleteSemanticMap;
+ readonly space: ProgramSpace;
+ readonly outer: NarrativeSelectionRef;
+ readonly triggers: NarrativeMomentRef;
+ readonly terminal: NarrativeMomentRef;
+}): LinerankSchedule {
+ assertLinerankHeader(input.header);
+ assertLinerankItemSpecSet(input.items);
+ assert(input.items.items.length > 0, "Linerank requires at least one Item.");
+ assertProgramSpaceIdentity(input.space);
+ const outer = locateSelectionOccurrences(input.map, input.outer, input.space);
+ assert(outer.length === input.items.items.length,
+ `Linerank board windows (${outer.length}) must equal Items (${input.items.items.length}).`);
+ const terminal = locateMomentOccurrences(input.map, input.terminal, input.space);
+ assert(terminal.length === 1, `Linerank terminal Moment requires exactly one occurrence; received ${terminal.length}.`);
+ const triggers = locateMomentOccurrences(input.map, input.triggers, input.space);
+ assert(triggers.length === input.items.items.length,
+ `Linerank trigger/item cardinality differs: ${triggers.length} triggers for ${input.items.items.length} Items.`);
+ const windows = outer.map((occurrence) => ({
+ startFrame: occurrence.start.frame,
+ endFrameExclusive: occurrence.end.frame,
+ }));
+ for (const [index, window] of windows.entries()) {
+ assert(window.endFrameExclusive > window.startFrame, `Linerank window ${index} is empty.`);
+ if (index > 0) assert(windows[index - 1]!.endFrameExclusive <= window.startFrame, `Linerank window ${index} overlaps the previous one.`);
+ }
+ const entries = input.items.items.map((item, index) => {
+ const triggerFrame = triggers[index]!.cue.frame;
+ assert(Number.isSafeInteger(triggerFrame), `Linerank trigger ${index} is not a frame.`);
+ return {
+ itemId: item.id,
+ rank: item.rank,
+ triggerFrame,
+ };
+ });
+ for (let index = 1; index < entries.length; index += 1) {
+ assert(entries[index]!.triggerFrame > entries[index - 1]!.triggerFrame,
+ "Linerank trigger frames are not strictly increasing.");
+ }
+ const result: LinerankSchedule = {
+ id: input.header.id,
+ windows,
+ terminalFrame: terminal[0]!.cue.frame,
+ entries,
+ };
+ assertLinerankSchedule(result, input.space);
+ return canonicalize(result) as unknown as LinerankSchedule;
+}
+
+export function assertLinerankSchedule(value: LinerankSchedule, space?: ProgramSpace): void {
+ identity(value.id, "LinerankSchedule.id");
+ assert(value.windows.length >= 1, "LinerankSchedule.windows is empty.");
+ frame(value.terminalFrame, "LinerankSchedule.terminalFrame");
+ assert(value.entries.length >= 1, "LinerankSchedule.entries is empty.");
+ const ids = new Set<string>();
+ for (const [index, window] of value.windows.entries()) {
+ frame(window.startFrame, `LinerankSchedule.windows.${index}.startFrame`);
+ frame(window.endFrameExclusive, `LinerankSchedule.windows.${index}.endFrameExclusive`);
+ assert(window.endFrameExclusive > window.startFrame, `LinerankSchedule.windows.${index} is empty.`);
+ if (index > 0) assert(value.windows[index - 1]!.endFrameExclusive <= window.startFrame,
+ `LinerankSchedule.windows.${index} overlaps the previous one.`);
+ }
+ const lastWindow = value.windows.at(-1)!;
+ assert(value.terminalFrame >= lastWindow.startFrame && value.terminalFrame < lastWindow.endFrameExclusive,
+ "LinerankSchedule.terminalFrame is outside the final window.");
+ for (const [index, entry] of value.entries.entries()) {
+ identity(entry.itemId, `LinerankSchedule.entries.${index}.itemId`);
+ assert(!ids.has(entry.itemId), `LinerankSchedule repeats ${entry.itemId}.`);
+ ids.add(entry.itemId);
+ integer(entry.rank, `LinerankSchedule.entries.${index}.rank`, 1);
+ frame(entry.triggerFrame, `LinerankSchedule.entries.${index}.triggerFrame`);
+ if (index > 0) assert(entry.triggerFrame > value.entries[index - 1]!.triggerFrame,
+ "LinerankSchedule trigger frames are not strictly increasing.");
+ const window = value.windows[index];
+ assert(window !== undefined, `LinerankSchedule entry ${entry.itemId} has no matching window.`);
+ assert(entry.triggerFrame >= window.startFrame && entry.triggerFrame < window.endFrameExclusive,
+ `LinerankSchedule entry ${entry.itemId} triggers outside its board window.`);
+ }
+ if (space !== undefined) {
+ assertProgramSpaceIdentity(space);
+ assert(value.windows.at(-1)!.endFrameExclusive <= programSpaceFrameCount(space), "LinerankSchedule exceeds ProgramSpace.");
+ }
+}
+
+export function createLinerankItemSet(): LinerankItemSet {
+ return { items: [] };
+}
+
+export function appendLinerankItem(set: LinerankItemSet, spec: LinerankItemSpec): LinerankItemSet {
+ assert(Array.isArray(set.items), "LinerankItemSet is invalid.");
+ assertLinerankItemSpec(spec);
+ assert(!set.items.some((item) => item.id === spec.id), `Linerank Item ${spec.id} is duplicated.`);
+ assert(!set.items.some((item) => item.rank === spec.rank), `Linerank Item rank ${spec.rank} is duplicated.`);
+ return canonicalize({ ...set, items: [...set.items, structuredClone(spec)] }) as unknown as LinerankItemSet;
+}
+
+export function buildLinerankProgram(
+ header: LinerankHeader,
+ frameValue: import("@hypit/spatial").SpatialFrame,
+ schedule: LinerankSchedule,
+ style: LinerankStyle,
+ title: string,
+ set: LinerankItemSet,
+): LinerankProgram {
+ assertLinerankHeader(header);
+ assertSpatialFrame(frameValue);
+ assertLinerankSchedule(schedule);
+ assertLinerankStyle(style);
+ assert(title.trim().length > 0, "LinerankProgram.title is empty.");
+ assert(schedule.entries.length === set.items.length, "Linerank Program item count differs from its Schedule.");
+ for (const [index, item] of set.items.entries()) {
+ assert(schedule.entries[index]?.itemId === item.id, "Linerank Program item order differs from its Schedule.");
+ }
+ const result: LinerankProgram = {
+ id: header.id,
+ frame: structuredClone(frameValue),
+ schedule: structuredClone(schedule),
+ style: structuredClone(style),
+ title: title.trim(),
+ items: structuredClone(set.items),
+ };
+ assertLinerankProgram(result);
+ return canonicalize(result) as unknown as LinerankProgram;
+}
+
+export function assertLinerankProgram(value: LinerankProgram): void {
+ assertLinerankSchedule(value.schedule);
+ assertSpatialFrame(value.frame);
+ assertLinerankStyle(value.style);
+ assert(value.title.trim().length > 0, "LinerankProgram.title is empty.");
+ assert(value.schedule.entries.length === value.items.length, "LinerankProgram item count differs from its Schedule.");
+ for (const [index, item] of value.items.entries()) {
+ assert(value.schedule.entries[index]?.itemId === item.id, "LinerankProgram item order differs from its Schedule.");
+ }
+}
+
+export function verifyLinerankMedia(_media: SynchronizedMedia): void {
+ // Reserved for future sound support; the board currently authors no audio.
+ void _media;
+}
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/style.ts b/examples/reference-reconstruction/packages/local-linerank/src/style.ts
new file mode 100644
index 00000000..ab567de9
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/style.ts
@@ -0,0 +1,112 @@
+import { assertFontArtifactRef, assertFontStackRef } from "@hypit/media";
+import type { FontArtifactRef, FontStackRef } from "@hypit/media";
+import { canonicalize } from "@hypit/protocol";
+import type { SvsRecipe } from "@hypit/svs";
+
+import { assertLinerankStyle } from "./schedule.js";
+import type { LinerankStyle, LinerankTextStyle } from "./types.js";
+
+const KEYS: readonly string[] = [
+ "paper-background", "rule-color", "rule-gap",
+ "title-size", "title-weight", "title-color", "title-line-height",
+ "number-size", "number-weight", "number-color",
+ "label-size", "label-weight", "label-color", "label-line-height",
+ "top-padding", "left-padding", "right-padding", "row-height", "row-gap", "number-width",
+ "type-frames-per-char",
+ "circle-color", "circle-width", "circle-frames",
+ "board-stack", "row-stack", "circle-stack",
+];
+
+function fail(recipe: SvsRecipe, message: string): never {
+ throw new Error(`Linerank Recipe ${recipe.path} ${message}`);
+}
+
+function known(recipe: SvsRecipe): void {
+ const set = new Set(KEYS);
+ const unknown = Object.keys(recipe.properties).filter((key) => !set.has(key));
+ if (unknown.length > 0) fail(recipe, `does not accept ${unknown.join(", ")}.`);
+}
+
+function number(recipe: SvsRecipe, name: string, fallback: number): number {
+ const value = recipe.properties[name];
+ if (value === undefined) return fallback;
+ if (typeof value !== "number" || !Number.isFinite(value)) fail(recipe, `${name} must be a finite number.`);
+ return value;
+}
+
+function integer(recipe: SvsRecipe, name: string, fallback: number): number {
+ const value = number(recipe, name, fallback);
+ if (!Number.isSafeInteger(value)) fail(recipe, `${name} must be an integer.`);
+ return value;
+}
+
+function text(recipe: SvsRecipe, name: string, fallback: string): string {
+ const value = recipe.properties[name];
+ if (value === undefined) return fallback;
+ if (typeof value !== "string" || value.trim().length === 0) fail(recipe, `${name} must be text.`);
+ return value.trim();
+}
+
+function exactFonts(value: FontStackRef | FontArtifactRef): FontArtifactRef[] {
+ if ("faces" in value) {
+ assertFontStackRef(value, "Linerank font");
+ return [...structuredClone(value.faces)];
+ }
+ assertFontArtifactRef(value, "Linerank font");
+ return [structuredClone(value)];
+}
+
+function typography(
+ recipe: SvsRecipe,
+ fonts: readonly FontArtifactRef[],
+ sizeName: string,
+ weightName: string,
+ colorName: string,
+ lineHeightName: string,
+ defaults: { readonly size: number; readonly weight: number; readonly color: string; readonly lineHeight: number },
+): LinerankTextStyle {
+ return {
+ fonts: structuredClone(fonts),
+ sizePx: number(recipe, sizeName, defaults.size),
+ weight: integer(recipe, weightName, defaults.weight),
+ color: text(recipe, colorName, defaults.color),
+ lineHeight: number(recipe, lineHeightName, defaults.lineHeight),
+ };
+}
+
+export function decodeLinerankStyle(
+ recipe: SvsRecipe,
+ font: FontStackRef | FontArtifactRef,
+): LinerankStyle {
+ known(recipe);
+ const fonts = exactFonts(font);
+ const style: LinerankStyle = {
+ paperBackground: text(recipe, "paper-background", "#ffffff"),
+ ruleColor: text(recipe, "rule-color", "#cfe0f5"),
+ ruleGapPx: number(recipe, "rule-gap", 64),
+ title: typography(recipe, fonts, "title-size", "title-weight", "title-color", "title-line-height", {
+ size: 40, weight: 700, color: "#111111", lineHeight: 1.15,
+ }),
+ number: typography(recipe, fonts, "number-size", "number-weight", "number-color", "label-line-height", {
+ size: 34, weight: 600, color: "#222222", lineHeight: 1.2,
+ }),
+ label: typography(recipe, fonts, "label-size", "label-weight", "label-color", "label-line-height", {
+ size: 36, weight: 500, color: "#111111", lineHeight: 1.2,
+ }),
+ topPaddingPx: number(recipe, "top-padding", 120),
+ leftPaddingPx: number(recipe, "left-padding", 56),
+ rightPaddingPx: number(recipe, "right-padding", 40),
+ rowHeightPx: number(recipe, "row-height", 72),
+ rowGapPx: number(recipe, "row-gap", 10),
+ numberWidthPx: number(recipe, "number-width", 64),
+ typeFramesPerChar: integer(recipe, "type-frames-per-char", 4),
+ circleColor: text(recipe, "circle-color", "#111111"),
+ circleWidthPx: number(recipe, "circle-width", 3),
+ circleFrames: integer(recipe, "circle-frames", 18),
+ boardStackingOrder: integer(recipe, "board-stack", 20),
+ rowStackingOrder: integer(recipe, "row-stack", 30),
+ circleStackingOrder: integer(recipe, "circle-stack", 40),
+ };
+ assertLinerankStyle(style);
+ return canonicalize(style) as unknown as LinerankStyle;
+}
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/surface.ts b/examples/reference-reconstruction/packages/local-linerank/src/surface.ts
new file mode 100644
index 00000000..4505a64a
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/surface.ts
@@ -0,0 +1,199 @@
+import { mediaTypes } from "@hypit/media";
+import { narrativeTypes } from "@hypit/narrative";
+import { programSpaceTypes } from "@hypit/program-space";
+import type { CanonicalValue, TypeRef } from "@hypit/protocol";
+import { semanticMapTypes } from "@hypit/semantic-map";
+import { spatialTypes } from "@hypit/spatial";
+import { svsRecipeType } from "@hypit/svs";
+import type { SvsRecipe } from "@hypit/svs";
+import { textTypes } from "@hypit/text";
+import type {
+ StructuredElement,
+ StructuredSurfaceHandler,
+ SurfaceRecordDraft,
+ SurfaceResolvedReference,
+ MarkupAttributeValue,
+} from "@hypit/markup";
+
+import { createLinerankFragment } from "./fragment.js";
+import type { LinerankFragmentItem } from "./fragment.js";
+import { linerankTypes } from "./manifest.js";
+import {
+ assertLinerankItemSpec,
+ sealLinerankHeader,
+} from "./schedule.js";
+import { decodeLinerankStyle } from "./style.js";
+import type { LinerankItemSpec } from "./types.js";
+
+function sameType(left: TypeRef, right: TypeRef): boolean {
+ return left.module.name === right.module.name
+ && left.module.version === right.module.version
+ && left.name === right.name;
+}
+
+function allowed(element: StructuredElement, names: readonly string[]): void {
+ const permit = new Set(names);
+ const unknown = Object.keys(element.attributes).filter((name) => !permit.has(name));
+ if (unknown.length > 0) throw new Error(`${element.name} has unsupported attributes ${unknown.join(", ")}.`);
+}
+
+function empty(element: StructuredElement): void {
+ if (element.children.some((child) => child.kind === "element" || child.value.trim().length > 0)) {
+ throw new Error(`${element.name} must be empty.`);
+ }
+}
+
+function text(element: StructuredElement, name: string, fallback?: string): string {
+ const value = element.attributes[name];
+ if (value === undefined && fallback !== undefined) return fallback;
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${element.name}.${name} must be text.`);
+ return value.trim();
+}
+
+function optionalText(element: StructuredElement, name: string): string | undefined {
+ const value = element.attributes[name];
+ if (value === undefined) return undefined;
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${element.name}.${name} must be text.`);
+ return value.trim();
+}
+
+function integer(element: StructuredElement, name: string): number | undefined {
+ const source = optionalText(element, name);
+ if (source === undefined) return undefined;
+ const value = Number(source);
+ if (!Number.isSafeInteger(value)) throw new Error(`${element.name}.${name} must be an integer.`);
+ return value;
+}
+
+function reference(
+ raw: MarkupAttributeValue | undefined,
+ label: string,
+ expected: TypeRef,
+ resolve: (path: string) => SurfaceResolvedReference | undefined,
+): SurfaceResolvedReference {
+ if (typeof raw !== "object" || raw.kind !== "reference") throw new Error(`${label} must be a reference.`);
+ const value = resolve(raw.path);
+ if (value === undefined || !sameType(value.type, expected)) throw new Error(`${label} has the wrong Type.`);
+ return value;
+}
+
+function inline<T>(value: SurfaceResolvedReference, label: string): T {
+ if (value.record?.value.kind !== "inline") throw new Error(`${label} must resolve during author compilation.`);
+ return value.record.value.value as unknown as T;
+}
+
+export const decodeLinerankStyleSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {
+ allowed(element, ["id", "recipe", "font"]);
+ empty(element);
+ const id = text(element, "id");
+ const recipeRef = reference(element.attributes.recipe, `${element.name}.recipe`, svsRecipeType, resolveReference);
+ const fontRef = reference(element.attributes.font, `${element.name}.font`, mediaTypes.fontStack, resolveReference);
+ const decoded = decodeLinerankStyle(inline<SvsRecipe>(recipeRef, `${element.name}.recipe`), inline(fontRef, `${element.name}.font`));
+ return {
+ records: [
+ { id, type: linerankTypes.style, value: { kind: "inline", value: decoded as unknown as CanonicalValue }, range: element.range },
+ ],
+ components: [], fragments: [],
+ };
+};
+
+function localName(element: StructuredElement): string {
+ return element.name.slice(element.name.lastIndexOf(":") + 1);
+}
+
+function textValue(
+ raw: MarkupAttributeValue | undefined,
+ label: string,
+ resolve: (path: string) => SurfaceResolvedReference | undefined,
+): string | SurfaceResolvedReference {
+ if (typeof raw === "string" && raw.trim().length > 0) return raw.trim();
+ return reference(raw, label, textTypes.text, resolve);
+}
+
+export const decodeLinerankBoardSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {
+ allowed(element, ["id", "map", "space", "frame", "during", "triggers", "terminal", "style", "title"]);
+ const id = text(element, "id");
+ const map = reference(element.attributes.map, `${element.name}.map`, semanticMapTypes.complete, resolveReference);
+ const space = reference(element.attributes.space, `${element.name}.space`, programSpaceTypes.programSpace, resolveReference);
+ const frame = reference(element.attributes.frame, `${element.name}.frame`, spatialTypes.frame, resolveReference);
+ const outer = reference(element.attributes.during, `${element.name}.during`, narrativeTypes.selection, resolveReference);
+ const triggers = reference(element.attributes.triggers, `${element.name}.triggers`, narrativeTypes.moment, resolveReference);
+ const terminal = reference(element.attributes.terminal, `${element.name}.terminal`, narrativeTypes.moment, resolveReference);
+ const style = reference(element.attributes.style, `${element.name}.style`, linerankTypes.style, resolveReference);
+
+ const records: SurfaceRecordDraft[] = [];
+ const headerId = `${id}.header`;
+ records.push({
+ id: headerId, type: linerankTypes.header,
+ value: { kind: "inline", value: sealLinerankHeader({ id }) as unknown as CanonicalValue },
+ range: element.range,
+ });
+
+ const titleValue = textValue(element.attributes.title, `${element.name}.title`, resolveReference);
+
+ const inputs: Record<string, typeof map.ref> = {
+ header: { kind: "record", id: headerId }, map: map.ref, space: space.ref, frame: frame.ref,
+ outer: outer.ref, triggers: triggers.ref, terminal: terminal.ref, style: style.ref,
+ };
+ if (typeof titleValue === "string") {
+ const titleId = `${id}.title`;
+ records.push({
+ id: titleId, type: textTypes.text,
+ value: { kind: "inline", value: { value: titleValue } as unknown as CanonicalValue },
+ range: element.range,
+ });
+ inputs.title = { kind: "record", id: titleId };
+ } else {
+ inputs.title = titleValue.ref;
+ }
+
+ const items: LinerankFragmentItem[] = [];
+ const itemIds = new Set<string>();
+ let index = 0;
+ for (const child of element.children) {
+ if (child.kind === "text") {
+ if (child.value.trim().length > 0) throw new Error(`${element.name} accepts BoardItem children only.`);
+ continue;
+ }
+ if (localName(child) !== "BoardItem") throw new Error(`${element.name} accepts BoardItem children only.`);
+ allowed(child, ["id", "rank", "label"]);
+ empty(child);
+ index += 1;
+ const suffix = String(index).padStart(4, "0");
+ const itemId = optionalText(child, "id") ?? `item-${suffix}`;
+ if (itemIds.has(itemId)) throw new Error(`${element.name} has duplicate Item id ${itemId}.`);
+ itemIds.add(itemId);
+ const rank = integer(child, "rank");
+ if (rank === undefined || rank < 1) throw new Error(`${child.name}.rank must be a positive integer.`);
+ const label = textValue(child.attributes.label, `${child.name}.label`, resolveReference);
+ const specId = `${id}.item.${suffix}.spec`;
+ const specName = `item-${suffix}-spec`;
+ if (typeof label === "string") {
+ const spec: LinerankItemSpec = { id: itemId, rank, label };
+ assertLinerankItemSpec(spec);
+ records.push({ id: specId, type: linerankTypes.itemSpec, value: { kind: "inline", value: spec as unknown as CanonicalValue }, range: child.range });
+ inputs[specName] = { kind: "record", id: specId };
+ items.push({ suffix, specName });
+ } else {
+ records.push({ id: specId, type: linerankTypes.textItemShell, value: { kind: "inline", value: { id: itemId, rank } as unknown as CanonicalValue }, range: child.range });
+ inputs[specName] = { kind: "record", id: specId };
+ const contentName = `item-${suffix}-content`;
+ inputs[contentName] = label.ref;
+ items.push({ suffix, specName, contentName });
+ }
+ }
+ if (items.length === 0) throw new Error(`${element.name} requires at least one BoardItem.`);
+
+ const fragment = createLinerankFragment(items);
+ return {
+ records,
+ components: [{
+ id, fragment: fragment.id, inputs,
+ outputs: {
+ schedule: `${id}.schedule`, program: `${id}.program`, visual: `${id}.visual`,
+ },
+ range: element.range,
+ }],
+ fragments: [fragment],
+ };
+};
diff --git a/examples/reference-reconstruction/packages/local-linerank/src/types.ts b/examples/reference-reconstruction/packages/local-linerank/src/types.ts
new file mode 100644
index 00000000..de1fc7ae
--- /dev/null
+++ b/examples/reference-reconstruction/packages/local-linerank/src/types.ts
@@ -0,0 +1,79 @@
+import type { FrameSpan } from "@hypit/composition";
+import type { FontArtifactRef } from "@hypit/media";
+import type { SpatialFrame } from "@hypit/spatial";
+
+export type LinerankHeader = {
+ readonly id: string;
+};
+
+export type LinerankScheduleEntry = {
+ readonly itemId: string;
+ readonly rank: number;
+ readonly triggerFrame: number;
+};
+
+export type LinerankSchedule = {
+ readonly id: string;
+ readonly windows: readonly FrameSpan[];
+ readonly terminalFrame: number;
+ readonly entries: readonly LinerankScheduleEntry[];
+};
+
+export type LinerankTextStyle = {
+ readonly fonts: readonly FontArtifactRef[];
+ readonly sizePx: number;
+ readonly weight: number;
+ readonly color: string;
+ readonly lineHeight: number;
+};
+
+export type LinerankStyle = {
+ readonly paperBackground: string;
+ readonly ruleColor: string;
+ readonly ruleGapPx: number;
+ readonly title: LinerankTextStyle;
+ readonly number: LinerankTextStyle;
+ readonly label: LinerankTextStyle;
+ readonly topPaddingPx: number;
+ readonly leftPaddingPx: number;
+ readonly rightPaddingPx: number;
+ readonly rowHeightPx: number;
+ readonly rowGapPx: number;
+ readonly numberWidthPx: number;
+ readonly typeFramesPerChar: number;
+ readonly circleColor: string;
+ readonly circleWidthPx: number;
+ readonly circleFrames: number;
+ readonly boardStackingOrder: number;
+ readonly rowStackingOrder: number;
+ readonly circleStackingOrder: number;
+};
+
+export type LinerankItemSpec = {
+ readonly id: string;
+ readonly rank: number;
+ readonly label: string;
+};
+
+/** Structural half of an Item whose visible label arrives on a Text graph edge. */
+export type LinerankTextItemShell = {
+ readonly id: string;
+ readonly rank: number;
+};
+
+export type LinerankItemSpecSet = {
+ readonly items: readonly LinerankItemSpec[];
+};
+
+export type LinerankItemSet = {
+ readonly items: readonly LinerankItemSpec[];
+};
+
+export type LinerankProgram = {
+ readonly id: string;
+ readonly frame: SpatialFrame;
+ readonly schedule: LinerankSchedule;
+ readonly style: LinerankStyle;
+ readonly title: string;
+ readonly items: readonly LinerankItemSpec[];
+};
diff --git a/examples/reference-reconstruction/scripts/render-board-preview.ts b/examples/reference-reconstruction/scripts/render-board-preview.ts
new file mode 100644
index 00000000..27406603
--- /dev/null
+++ b/examples/reference-reconstruction/scripts/render-board-preview.ts
@@ -0,0 +1,164 @@
+/**
+ * Local, Provider-free render of the lined-paper ranking board to a PNG still.
+ * Builds the board Program directly (bypassing the paid schedule/alignment path)
+ * and compiles it through the local HyperFrames Runtime, exactly as
+ * packages/hyperframes/test/browser-visual.test.ts does.
+ *
+ * Run with: node --import tsx examples/reference-reconstruction/scripts/render-board-preview.ts
+ */
+import { createHash } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { mkdir, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+
+import { sealProgramSpace } from "@hypit/program-space";
+import { sealComposition } from "@hypit/composition";
+import { compileHyperframesDocument, materializeHyperframesHtml } from "@hypit/hyperframes";
+import { decodeOpenFontFaceSurface } from "@hypit/fonts-open";
+import type { FontArtifactRef } from "@hypit/media";
+import type { SvsRecipe } from "@hypit/svs";
+
+import {
+ buildLinerankProgram,
+ renderLinerankBoard,
+} from "@hypit/local-linerank";
+import { decodeLinerankStyle } from "@hypit/local-linerank";
+
+function digest(bytes: Uint8Array): string {
+ return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
+}
+
+const hyperframesCli = createRequire(path.join(process.cwd(), "packages/provider-hyperframes-local/package.json"))
+ .resolve("hyperframes/bin/hyperframes.mjs");
+
+async function installedOpenFont(
+ family: string,
+ weight: number,
+ style: "normal" | "italic",
+): Promise<{ readonly font: FontArtifactRef; readonly bytes: ReadonlyMap<string, Uint8Array> }> {
+ const bytes = new Map<string, Uint8Array>();
+ const output = await decodeOpenFontFaceSurface({
+ sourceName: "render-board-preview.svml",
+ element: {
+ kind: "element",
+ name: "fonts:Face",
+ attributes: { id: `${family}-${weight}-${style}`, family, weight: String(weight), style },
+ children: [],
+ range: { start: 0, end: 1 },
+ },
+ resolveReference: () => undefined,
+ resolveAsset(request) {
+ if (request.bytes === undefined) throw new Error(`Open font ${family} resolved without bytes.`);
+ const copy = Uint8Array.from(request.bytes);
+ const artifactDigest = digest(copy);
+ bytes.set(artifactDigest, copy);
+ return {
+ artifact: {
+ kind: "blob",
+ digest: artifactDigest,
+ size: copy.byteLength,
+ mediaType: request.mediaType,
+ },
+ };
+ },
+ });
+ const stored = output.records[0]?.value;
+ if (stored?.kind !== "inline") throw new Error("Open font did not resolve inline.");
+ return { font: stored.value as FontArtifactRef, bytes };
+}
+
+async function main() {
+ const { font, bytes } = await installedOpenFont("shadows-into-light", 400, "normal");
+
+ const recipe: SvsRecipe = {
+ path: "studio.linerank.board",
+ properties: {
+ "paper-background": "#F7F7F4", "rule-color": "#D8DEE6", "rule-gap": 64,
+ "title-size": 40, "title-weight": 700, "title-color": "#111111", "title-line-height": 1.15,
+ "number-size": 34, "number-weight": 600, "number-color": "#222222",
+ "label-size": 38, "label-weight": 500, "label-color": "#111111", "label-line-height": 1.2,
+ "top-padding": 188, "left-padding": 56, "right-padding": 40,
+ "row-height": 74, "row-gap": 12, "number-width": 66,
+ "type-frames-per-char": 4,
+ "circle-color": "#111111", "circle-width": 4, "circle-frames": 20,
+ "board-stack": 20, "row-stack": 30, "circle-stack": 40,
+ },
+ };
+ const style = decodeLinerankStyle(recipe, font);
+
+ // 720x1280 at 30fps; five board windows mirroring the reference's five appearances.
+ const space = sealProgramSpace({ durationSec: 45, frameRate: { numerator: 30, denominator: 1 } });
+ const frame = { xPx: 0, yPx: 0, widthPx: 720, heightPx: 1280 };
+
+ const windows = [
+ { startFrame: 85, endFrameExclusive: 125 },
+ { startFrame: 283, endFrameExclusive: 321 },
+ { startFrame: 488, endFrameExclusive: 521 },
+ { startFrame: 667, endFrameExclusive: 680 },
+ { startFrame: 944, endFrameExclusive: 975 },
+ ];
+ const entries = [
+ { itemId: "item-5", rank: 5, triggerFrame: 85 },
+ { itemId: "item-4", rank: 4, triggerFrame: 283 },
+ { itemId: "item-3", rank: 3, triggerFrame: 488 },
+ { itemId: "item-2", rank: 2, triggerFrame: 667 },
+ { itemId: "item-1", rank: 1, triggerFrame: 944 },
+ ];
+ const schedule = { id: "board", windows, terminalFrame: 962, entries };
+ const items = [
+ { id: "item-5", rank: 5, label: "Instagram" },
+ { id: "item-4", rank: 4, label: "AI Courses" },
+ { id: "item-3", rank: 3, label: "YouTube" },
+ { id: "item-2", rank: 2, label: "Twitter/X" },
+ { id: "item-1", rank: 1, label: "The Rundown" },
+ ];
+ const program = buildLinerankProgram(
+ { id: "board" },
+ frame,
+ schedule,
+ style,
+ "Top 5 Most Popular Ways to learn AI",
+ { items },
+ );
+ const track = renderLinerankBoard(space, program);
+
+ const composition = sealComposition({
+ id: "board-proof",
+ canvas: { width: 720, height: 1280, clearColor: "#09090B" },
+ tracks: [track],
+ });
+ const document = compileHyperframesDocument(composition, space);
+ const html = materializeHyperframesHtml(document, (artifact) => {
+ const name = `${artifact.digest.replace(/[^a-zA-Z0-9]/g, "")}.woff2`;
+ return `./${name}`;
+ });
+
+ const temp = path.join(process.cwd(), "examples/reference-reconstruction/.render-board");
+ await mkdir(path.join(temp, "frames"), { recursive: true });
+ for (const [artifactDigest, fileBytes] of bytes) {
+ const name = `${artifactDigest.replace(/[^a-zA-Z0-9]/g, "")}.woff2`;
+ await writeFile(path.join(temp, name), fileBytes);
+ }
+ await writeFile(path.join(temp, "index.html"), html);
+
+ const result = spawnSync(process.execPath, [
+ hyperframesCli, "render", temp,
+ "--format", "png-sequence",
+ "--output", path.join(temp, "frames"),
+ "--fps", "30",
+ "--workers", "1",
+ "--no-browser-gpu",
+ "--no-best-effort",
+ "--quiet",
+ ], { encoding: "utf8", timeout: 180_000 });
+ if (result.status !== 0) {
+ throw new Error(`Hyperframes render failed:\n${result.stdout}\n${result.stderr}`);
+ }
+ console.log("RENDER_OK", result.stdout.split("\n").slice(0, 5).join(" "));
+}
+
+main().catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+});
diff --git a/examples/reference-reconstruction/studio.svs b/examples/reference-reconstruction/studio.svs
new file mode 100644
index 00000000..90e4564f
--- /dev/null
+++ b/examples/reference-reconstruction/studio.svs
@@ -0,0 +1,123 @@
+<?svml using="@hypit/svs@1"?>
+
+<sheet version="1" id="studio">
+ speech.normal {
+ language: en;
+ pace: normal;
+ min: 4;
+ max: 15;
+ rounding: round;
+ }
+
+ speaker.host {
+ composition-stability: soft-locked;
+ camera-motion: none;
+ edit-rhythm: continuous-take;
+ performance: natural-explainer;
+ gesture: natural;
+ }
+
+ film.vertical {
+ background: #09090B;
+ }
+
+ speech.visual { fit: cover; }
+
+ caption.primary {
+ cue-min-words: 2;
+ cue-max-words: 7;
+ stack-order: 70;
+ x: 0.5;
+ y: 0.8;
+ anchor-x: center;
+ anchor-y: bottom;
+ width: 0.9;
+ size: 46;
+ line-height: 1;
+ align: center;
+ fill: #FFFFFF;
+ stroke-color: #09090B;
+ stroke-width: 5;
+ shadow-color: #000000;
+ shadow-opacity: 0.6;
+ shadow-x: 0;
+ shadow-y: 3;
+ shadow-blur: 8;
+ background: #09090B66;
+ padding: 8 16;
+ radius: 10;
+ }
+
+ linerank.board {
+ paper-background: #F7F7F4;
+ rule-color: #D8DEE6;
+ rule-gap: 64;
+ title-size: 40;
+ title-weight: 700;
+ title-color: #111111;
+ title-line-height: 1.15;
+ number-size: 34;
+ number-weight: 600;
+ number-color: #222222;
+ label-size: 38;
+ label-weight: 500;
+ label-color: #111111;
+ label-line-height: 1.2;
+ top-padding: 188;
+ left-padding: 56;
+ right-padding: 40;
+ row-height: 74;
+ row-gap: 12;
+ number-width: 66;
+ type-frames-per-char: 4;
+ circle-color: #111111;
+ circle-width: 4;
+ circle-frames: 20;
+ board-stack: 20;
+ row-stack: 30;
+ circle-stack: 40;
+ }
+
+ media.product {
+ stack-order: 45;
+ fit: contain;
+ frame-paint: #111116;
+ clip: rounded;
+ radius: 24;
+ border-width: 1;
+ border-style: solid;
+ border-color: #FFFFFF30;
+ shadows: 0 10 24 0 #00000066;
+ }
+
+ motion.product {
+ enter: slide;
+ enter-frames: 6;
+ enter-direction: up;
+ enter-easing: ease-out;
+ exit: fade;
+ exit-frames: 6;
+ exit-easing: ease-in;
+ }
+
+ media.thumb {
+ stack-order: 42;
+ fit: cover;
+ frame-paint: #111116;
+ clip: rounded;
+ radius: 16;
+ border-width: 1;
+ border-style: solid;
+ border-color: #FFFFFF30;
+ shadows: 0 10 24 0 #00000066;
+ }
+
+ motion.thumb {
+ enter: pop;
+ enter-frames: 5;
+ enter-easing: ease-out;
+ exit: fade;
+ exit-frames: 4;
+ exit-easing: ease-in;
+ }
+</sheet>
diff --git a/package.json b/package.json
index 1b3b0264..d7f37499 100644
--- a/package.json
+++ b/package.json
@@ -97,6 +97,7 @@
"@hypit/typography-track": "workspace:*",
"@hypit/visual-ir": "workspace:*",
"@hypit/whisperx": "workspace:*",
+ "@hypit/local-linerank": "workspace:*",
"@types/node": "24.10.1",
"tsx": "4.21.0",
"typescript": "5.9.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 24f27104..7cf42cc4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -77,6 +77,9 @@ importers:
'@hypit/image-transform':
specifier: workspace:*
version: link:packages/image-transform
+ '@hypit/local-linerank':
+ specifier: workspace:*
+ version: link:examples/reference-reconstruction/packages/local-linerank
'@hypit/media':
specifier: workspace:*
version: link:packages/media
@@ -225,6 +228,55 @@ importers:
specifier: ^1.6.4
+ examples/reference-reconstruction/packages/local-linerank:
+ dependencies:
+ '@hypit/artifact':
+ specifier: workspace:*
+ version: link:../../../../packages/artifact
+ '@hypit/component-kit':
+ specifier: workspace:*
+ version: link:../../../../packages/component-kit
+ '@hypit/composition':
+ specifier: workspace:*
+ version: link:../../../../packages/composition
+ '@hypit/elaborator':
+ specifier: workspace:*
+ version: link:../../../../packages/elaborator
+ '@hypit/markup':
+ specifier: workspace:*
+ version: link:../../../../packages/markup
+ '@hypit/media':
+ specifier: workspace:*
+ version: link:../../../../packages/media
+ '@hypit/narrative':
+ specifier: workspace:*
+ version: link:../../../../packages/narrative
+ '@hypit/program-space':
+ specifier: workspace:*
+ version: link:../../../../packages/program-space
+ '@hypit/protocol':
+ specifier: workspace:*
+ version: link:../../../../packages/protocol
+ '@hypit/semantic-map':
+ specifier: workspace:*
+ version: link:../../../../packages/semantic-map
+ '@hypit/spatial':
+ specifier: workspace:*
+ version: link:../../../../packages/spatial
+ '@hypit/svs':
+ specifier: workspace:*
+ version: link:../../../../packages/svs
+ '@hypit/temporal':
+ specifier: workspace:*
+ version: link:../../../../packages/temporal
+ '@hypit/text':
+ specifier: workspace:*
+ version: link:../../../../packages/text
+ devDependencies:
+ '@hypit/core':
+ specifier: workspace:*
+ version: link:../../../../packages/core
+
packages/artifact:
dependencies:
'@hypit/protocol':