Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(telemetry): per-tag, provenance, and failure-taxonomy properties on render events (#4004)
miga-heygen3704863d966a
diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.tsindex a3cd3cf50d..0040430f71 100644--- a/packages/cli/src/commands/render.test.ts+++ b/packages/cli/src/commands/render.test.ts@@ -1861,4 +1861,28 @@ describe("render command batch options", () => {}, 60_000);});+describe("normalizeStageCode", () => {+ const { normalizeStageCode } = renderModule;++ it("maps every known updateJobStatus stage string to its code", () => {+ expect(normalizeStageCode("Queued")).toBe("queued");+ expect(normalizeStageCode("Compiling composition")).toBe("compiling_composition");+ expect(normalizeStageCode("Extracting video frames")).toBe("extracting_video_frames");+ expect(normalizeStageCode("Processing audio tracks")).toBe("processing_audio_tracks");+ expect(normalizeStageCode("Starting frame capture")).toBe("starting_frame_capture");+ expect(normalizeStageCode("Render complete")).toBe("render_complete");+ expect(normalizeStageCode("Render cancelled")).toBe("render_cancelled");+ expect(normalizeStageCode("pipeline")).toBe("pipeline");+ });++ it("slugifies an unrecognized stage string instead of bucketing it as unknown", () => {+ expect(normalizeStageCode("Some New Stage!")).toBe("some_new_stage");+ });++ it("falls back to unknown only when slugifying produces nothing usable", () => {+ expect(normalizeStageCode("")).toBe("unknown");+ expect(normalizeStageCode("!!!")).toBe("unknown");+ });+});+// Variables-helper tests live in `../utils/variables.test.ts`.diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.tsindex a15b11b0e2..b7d0ce025d 100644--- a/packages/cli/src/commands/render.ts+++ b/packages/cli/src/commands/render.ts@@ -1500,6 +1500,37 @@ function reportDeParallelRouterBreakerTrip(quiet: boolean): void {);}+/**+ * `job.currentStage`/`failedStage` are free-text progress labels+ * (`updateJobStatus`'s callers each pass their own human sentence — "Compiling+ * composition", "Extracting video frames", …), which makes an exact string+ * property unbounded in a telemetry event. This maps the known set to a+ * stable snake_case code, and slugifies anything unrecognized instead of+ * bucketing it into a single opaque "unknown" — a future stage string still+ * gets a distinct, readable code without needing this map updated first.+ */+const KNOWN_STAGE_CODES: Readonly<Record<string, string>> = {+ Queued: "queued",+ "Compiling composition": "compiling_composition",+ "Extracting video frames": "extracting_video_frames",+ "Processing audio tracks": "processing_audio_tracks",+ "Starting frame capture": "starting_frame_capture",+ "Render complete": "render_complete",+ "Render cancelled": "render_cancelled",+ pipeline: "pipeline",+};++export function normalizeStageCode(stage: string): string {+ const known = KNOWN_STAGE_CODES[stage];+ if (known) return known;+ const slug = stage+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "_")+ .replace(/^_+|_+$/g, "");+ return slug || "unknown";+}+function handleRenderError(error: unknown,options: RenderOptions,@@ -1520,6 +1551,14 @@ function handleRenderError(elapsedMs: Date.now() - startTime,errorMessage: message,failedStage,+ // A bucketable failure taxonomy alongside the free-text error_message+ // above: error.name is one of ~20 typed producer error classes+ // (CaptureFailure, DrawElementCaptureError, SwiftShaderAssertionError, …);+ // failed_stage_code is the same job.currentStage value normalized to a+ // stable code. Error-conditional by nature — there is no equivalent on+ // the render_complete success path, since nothing failed to name.+ errorName: error instanceof Error ? error.name : "unknown",+ failedStageCode: normalizeStageCode(failedStage || "pipeline"),...renderJobObservabilityTelemetryPayload(job),...getMemorySnapshot(),});@@ -1622,6 +1661,9 @@ function trackRenderMetrics(dePreInversionWorkers: perf?.drawElement?.preInversionWorkers,compositionElementCount: perf?.drawElement?.compositionElementCount,compositionElementCountSource: perf?.drawElement?.compositionElementCountSource,+ compositionElementTags: perf?.drawElement?.compositionElementTags,+ arollVideoCount: perf?.drawElement?.arollVideoCount,+ heygenVideoCount: perf?.drawElement?.heygenVideoCount,deShortBand: perf?.drawElement?.shortBand,deParallelRouter: perf?.drawElement?.parallelRouter,dePreRouterWorkers: perf?.drawElement?.preRouterWorkers,diff --git a/packages/cli/src/telemetry/events.ts b/packages/cli/src/telemetry/events.tsindex 838b1cfc30..a996748c20 100644--- a/packages/cli/src/telemetry/events.ts+++ b/packages/cli/src/telemetry/events.ts@@ -75,6 +75,9 @@ export interface RenderObservabilityTelemetryPayload {captureDePreInversionWorkers?: number;captureCompositionElementCount?: number;captureCompositionElementCountSource?: string;+ captureCompositionElementTags?: Readonly<Record<string, number>>;+ captureArollVideoCount?: number;+ captureHeygenVideoCount?: number;captureDeShortBand?: string;captureDeParallelRouter?: string;captureDeGpuRenderer?: string;@@ -137,6 +140,9 @@ function renderObservabilityEventProperties(props: RenderObservabilityTelemetryPde_pre_inversion_workers: props.captureDePreInversionWorkers,composition_element_count: props.captureCompositionElementCount,composition_element_count_source: props.captureCompositionElementCountSource,+ composition_element_tags: props.captureCompositionElementTags,+ aroll_video_count: props.captureArollVideoCount,+ heygen_video_count: props.captureHeygenVideoCount,de_short_band: props.captureDeShortBand,de_parallel_router: props.captureDeParallelRouter,gpu_renderer: props.captureDeGpuRenderer,@@ -276,6 +282,9 @@ export function trackRenderComplete(dePreInversionWorkers?: number;compositionElementCount?: number;compositionElementCountSource?: string;+ compositionElementTags?: Readonly<Record<string, number>>;+ arollVideoCount?: number;+ heygenVideoCount?: number;deShortBand?: string;deParallelRouter?: string;dePreRouterWorkers?: number;@@ -380,6 +389,9 @@ export function trackRenderComplete(de_pre_inversion_workers: props.dePreInversionWorkers,composition_element_count: props.compositionElementCount,composition_element_count_source: props.compositionElementCountSource,+ composition_element_tags: props.compositionElementTags,+ aroll_video_count: props.arollVideoCount,+ heygen_video_count: props.heygenVideoCount,de_short_band: props.deShortBand,de_parallel_router: props.deParallelRouter,de_pre_router_workers: props.dePreRouterWorkers,@@ -457,6 +469,10 @@ export function trackRenderError(gpu?: boolean;source?: "cli" | "studio";failedStage?: string;+ /** One of ~20 typed producer error classes (CaptureFailure, DrawElementCaptureError, …), or "unknown" for a non-Error throw. */+ errorName?: string;+ /** failedStage normalized to a stable snake_case code. */+ failedStageCode?: string;errorMessage?: string;elapsedMs?: number;peakMemoryMb?: number;@@ -477,6 +493,8 @@ export function trackRenderError(gpu: props.gpu,source: props.source ?? "cli",failed_stage: props.failedStage,+ error_name: props.errorName,+ failed_stage_code: props.failedStageCode,error_message: props.errorMessage ? redactTelemetryMessage(props.errorMessage) : undefined,elapsed_ms: props.elapsedMs,peak_memory_mb: props.peakMemoryMb,diff --git a/packages/cli/src/telemetry/renderObservability.ts b/packages/cli/src/telemetry/renderObservability.tsindex c802edf6c1..40afe4de42 100644--- a/packages/cli/src/telemetry/renderObservability.ts+++ b/packages/cli/src/telemetry/renderObservability.ts@@ -44,6 +44,9 @@ export function renderObservabilityTelemetryPayload(captureDePreInversionWorkers: capture.dePreInversionWorkers,captureCompositionElementCount: capture.compositionElementCount,captureCompositionElementCountSource: capture.compositionElementCountSource,+ captureCompositionElementTags: capture.compositionElementTags,+ captureArollVideoCount: capture.arollVideoCount,+ captureHeygenVideoCount: capture.heygenVideoCount,captureDeShortBand: capture.deShortBand,captureDeParallelRouter: capture.deParallelRouter,captureDeGpuRenderer: capture.deGpuRenderer,diff --git a/packages/producer/src/services/render/observability.ts b/packages/producer/src/services/render/observability.tsindex c757b986bd..0b77548363 100644--- a/packages/producer/src/services/render/observability.ts+++ b/packages/producer/src/services/render/observability.ts@@ -74,7 +74,7 @@ export interface RenderCaptureObservability {* Element count for the short-comp band gate (`resolveCompositionElementCount`):* the LIVE DOM size from the already-running probe session when one is* initialized, falling back to a static scan of the compiled HTML- * (`countElementTags`) otherwise. Live is authoritative — a static scan+ * (`scanElementTags`) otherwise. Live is authoritative — a static scan* cannot see elements a composition's own script creates at runtime.** Emitted on every render, not just inverted ones — this is the variable the@@ -93,6 +93,30 @@ export interface RenderCaptureObservability {* unlock for the band.*/compositionElementCountSource?: "live" | "static";+ /**+ * Per-tag breakdown of the same static scan behind `compositionElementCount`+ * — one shared regex pass feeds both fields, so a fleet query summing this+ * map's values always reconciles against the integer. Capped by+ * `scanElementTags` (top tags by count + an `other` bucket) so a+ * pathological composition's distinct tag count can't inflate the event+ * payload. Only set when+ * `compositionElementCountSource` is "static" — the live path measures a+ * DOM node count directly and never runs this scan.+ */+ compositionElementTags?: Readonly<Record<string, number>>;+ /**+ * `<video data-aroll="true">` elements from the same static scan as+ * `compositionElementTags`. Only set when `compositionElementCountSource`+ * is "static".+ */+ arollVideoCount?: number;+ /**+ * `<video data-media-source="heygen">` elements from the same static scan+ * as `compositionElementTags` — the media-use skill stamps this attribute+ * only when the mounted video's ledger record traces to the "heygen.video"+ * provider. Only set when `compositionElementCountSource` is "static".+ */+ heygenVideoCount?: number;/*** Short-comp band decision, emitted only when the band is DECISIVE — every* other inversion-eligibility condition passed and only the floor (250 vsdiff --git a/packages/producer/src/services/render/perfSummary.ts b/packages/producer/src/services/render/perfSummary.tsindex fcc4f68dbf..6a3b1558c9 100644--- a/packages/producer/src/services/render/perfSummary.ts+++ b/packages/producer/src/services/render/perfSummary.ts@@ -90,6 +90,12 @@ export interface DrawElementPerfInput {compositionElementCount?: number;/** Provenance of the element count: "live" (probe DOM, trusted to gate) | "static" (source scan, not). */compositionElementCountSource?: "live" | "static";+ /** Per-tag breakdown of the same static scan behind compositionElementCount; only set when the source above is "static". */+ compositionElementTags?: Readonly<Record<string, number>>;+ /** `<video data-aroll="true">` count from the same static scan; only set when compositionElementCountSource is "static". */+ arollVideoCount?: number;+ /** `<video data-media-source="heygen">` count from the same static scan; only set when compositionElementCountSource is "static". */+ heygenVideoCount?: number;/** Short-comp band decision when the band was DECISIVE: "applied" (inverts once HF_DE_SHORT_BAND_ROUTE is on; counterfactual in the baseline release) | "skipped_elements" (element ceiling was the only blocker); unset when the band could not have affected this render. */shortBand?: "applied" | "skipped_elements" | "unmeasured";parallelRouter?: "routed" | "reverted";@@ -135,6 +141,9 @@ function aggregateDrawElement(preInversionWorkers: de.preInversionWorkers,compositionElementCount: de.compositionElementCount,compositionElementCountSource: de.compositionElementCountSource,+ compositionElementTags: de.compositionElementTags,+ arollVideoCount: de.arollVideoCount,+ heygenVideoCount: de.heygenVideoCount,shortBand: de.shortBand,parallelRouter: de.parallelRouter ?? "none",preRouterWorkers: de.preRouterWorkers,diff --git a/packages/producer/src/services/renderOrchestrator.test.ts b/packages/producer/src/services/renderOrchestrator.test.tsindex b2e2252e91..760d97be45 100644--- a/packages/producer/src/services/renderOrchestrator.test.ts+++ b/packages/producer/src/services/renderOrchestrator.test.ts@@ -41,7 +41,7 @@ import {shouldRetryViaPinnedFallback,isDeRendererStallError,isSequentialCaptureStallError,- countElementTags,+ scanElementTags,envInt,isDeParallelRouterEnabled,mergeWorkerInitObservability,@@ -2075,14 +2075,14 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {});});- describe("countElementTags", () => {+ describe("scanElementTags", () => {it("counts closing tags", () => {- expect(countElementTags("<div><span>a</span></div>")).toBe(2);+ expect(scanElementTags("<div><span>a</span></div>").total).toBe(2);});it("counts void elements — an image gallery must not read as a tiny comp", () => {- expect(countElementTags("<img><br><hr>")).toBe(3);- expect(countElementTags('<img src="a.png"><IMG SRC="b.png">')).toBe(2);+ expect(scanElementTags("<img><br><hr>").total).toBe(3);+ expect(scanElementTags('<img src="a.png"><IMG SRC="b.png">').total).toBe(2);});// Review-flagged blocker (v1): SVG elements are neither closing-tag-shaped@@ -2092,14 +2092,14 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {// measured 1.8x regression case is made of. The ceiling cannot bound an// error that has no bound of its own.it("counts self-closing SVG elements — the 40k-node regression case must not read as empty", () => {- expect(countElementTags("<circle/>".repeat(40000))).toBe(40000);- expect(countElementTags('<path d="M0 0 L1 1" stroke="red" />')).toBe(1);- expect(countElementTags("<feGaussianBlur stdDeviation='2'/>")).toBe(1);+ expect(scanElementTags("<circle/>".repeat(40000)).total).toBe(40000);+ expect(scanElementTags('<path d="M0 0 L1 1" stroke="red" />').total).toBe(1);+ expect(scanElementTags("<feGaussianBlur stdDeviation='2'/>").total).toBe(1);});it("does not double-count a self-closed void element (still just 1)", () => {- expect(countElementTags('<img src="a.png"/>')).toBe(1);- expect(countElementTags('<img src="a.png" />')).toBe(1);+ expect(scanElementTags('<img src="a.png"/>').total).toBe(1);+ expect(scanElementTags('<img src="a.png" />').total).toBe(1);});it("does not false-positive on minified JS division-after-comparison (the self-closing alt's real risk)", () => {@@ -2108,16 +2108,16 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {// starting a match — but it still requires the literal two-char "/>"// sequence, and here a "c" sits between the "/" and the ">", so// backtracking never finds one and it correctly fails to match.- expect(countElementTags("if(a<b/c>d){}")).toBe(0);+ expect(scanElementTags("if(a<b/c>d){}").total).toBe(0);});it("does not false-positive on inline-script comparisons or void-prefixed words", () => {// Script bodies are stripped wholesale (with their own closing tag), so// nothing inside can match — including "<breadth" / "<imgWidth", which// would anyway fail the \b word boundary.- expect(countElementTags("<script>if (a < b && x <breadth && y <imgWidth) {}</script>")).toBe(- 0,- );+ expect(+ scanElementTags("<script>if (a < b && x <breadth && y <imgWidth) {}</script>").total,+ ).toBe(0);});// Review finding: the `</[a-zA-Z]` alternation matches ANY "</" + letter,@@ -2126,16 +2126,17 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {// on the ~83% of renders with no probe, for which this scan is the only// element signal.it("does not count closing tags written inside inline script strings", () => {- expect(countElementTags('<div></div><script>const h = "</div></div></div>";</script>')).toBe(- 1,- );expect(- countElementTags("<p></p><script>const t = words.map(w => `</span>`).join('');</script>"),+ scanElementTags('<div></div><script>const h = "</div></div></div>";</script>').total,+ ).toBe(1);+ expect(+ scanElementTags("<p></p><script>const t = words.map(w => `</span>`).join('');</script>")+ .total,).toBe(1);});it("strips <style> bodies too — CSS content strings can carry the same shapes", () => {- expect(countElementTags('<div></div><style>a::after{content:"</div>"}</style>')).toBe(1);+ expect(scanElementTags('<div></div><style>a::after{content:"</div>"}</style>').total).toBe(1);});// CodeQL "incomplete multi-character sanitization": a single-pass replace@@ -2145,28 +2146,93 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {it("strips script tags that reform after one pass", () => {// Inner <script> removed by pass 1 leaves "<script>alert(1)</script>",// which pass 2 removes. A single pass would leave a stray tag behind.- expect(countElementTags("<div></div><scr<script></script>ipt>alert(1)</script>")).toBe(1);+ expect(scanElementTags("<div></div><scr<script></script>ipt>alert(1)</script>").total).toBe(+ 1,+ );});it("terminates on input with no closing tag rather than looping", () => {- expect(countElementTags("<div></div><script>unterminated")).toBe(1);+ expect(scanElementTags("<div></div><script>unterminated").total).toBe(1);});it("strips multiple and attributed script blocks, not just the first", () => {expect(- countElementTags(+ scanElementTags('<div></div><script type="module">"</span>"</script><script>"</span>"</script>',- ),+ ).total,).toBe(1);});it("is stable on empty and malformed input rather than throwing", () => {- expect(countElementTags("")).toBe(0);- expect(countElementTags("<<<>>>")).toBe(0);+ expect(scanElementTags("").total).toBe(0);+ expect(scanElementTags("<<<>>>").total).toBe(0);});it("scales to a large document without a full parse", () => {- expect(countElementTags("<p>x</p>".repeat(40000))).toBe(40000);+ expect(scanElementTags("<p>x</p>".repeat(40000)).total).toBe(40000);+ });++ it("groups mixed native and custom hf-* tags by raw tag name", () => {+ const html =+ "<div><span>a</span></div><hf-caption></hf-caption><hf-audio-group></hf-audio-group><div></div>";+ const scan = scanElementTags(html);+ expect(scan.byTag).toEqual({ div: 2, span: 1, "hf-caption": 1, "hf-audio-group": 1 });+ expect(scan.total).toBe(5);+ });++ it("normalizes case so <DIV>/<Div>/<div> collapse into one key", () => {+ const scan = scanElementTags("<DIV></DIV><Div></Div><div></div>");+ expect(scan.byTag).toEqual({ div: 3 });+ });++ it("count/map consistency: the sum of byTag always equals total", () => {+ const html =+ '<div><img src="a.png"><hf-caption></hf-caption></div><circle/><path d="M0 0" />' ++ "<hf-audio-group></hf-audio-group>".repeat(3);+ const scan = scanElementTags(html);+ const sum = Object.values(scan.byTag).reduce((a, b) => a + b, 0);+ expect(sum).toBe(scan.total);+ });++ it("caps distinct reported tags, folding the overflow into an `other` bucket", () => {+ // 60 distinct single-use tag names, well past the 50-tag cap. "div"+ // (100 uses) takes the top rank, leaving only 49 of the 50 slots for+ // the 60 distinct tags — 11 of them fold into "other".+ const distinctTags = Array.from({ length: 60 }, (_, i) => `hf-tag-${i}`);+ const html = "<div></div>".repeat(100) + distinctTags.map((t) => `<${t}></${t}>`).join("");+ const scan = scanElementTags(html);+ expect(Object.keys(scan.byTag).length).toBe(51); // 50 reported + "other"+ expect(scan.byTag.div).toBe(100);+ expect(scan.byTag.other).toBe(11); // 60 distinct tags - 49 reported = 11 folded in+ const sum = Object.values(scan.byTag).reduce((a, b) => a + b, 0);+ expect(sum).toBe(scan.total);+ expect(scan.total).toBe(100 + 60);+ });++ it("counts <video data-aroll=true> elements, not audio/img carrying the same attribute", () => {+ const html =+ '<video data-aroll="true" src="a.mp4"></video>' ++ '<video src="b.mp4"></video>' ++ '<audio data-aroll="true" src="a.mp3"></audio>' ++ '<img data-aroll="true" src="a.png" />';+ expect(scanElementTags(html).arollVideoCount).toBe(1);+ });++ it("counts <video data-media-source=heygen> elements only, not other provider values", () => {+ const html =+ '<video data-media-source="heygen" src="a.mp4"></video>' ++ '<video src="b.mp4"></video>' ++ '<video data-media-source="ltx.local" src="c.mp4"></video>' ++ '<audio data-media-source="heygen" src="a.mp3"></audio>';+ expect(scanElementTags(html).heygenVideoCount).toBe(1);+ });++ it("reports zero (not undefined) arollVideoCount/heygenVideoCount and an empty byTag when nothing matches", () => {+ const scan = scanElementTags("plain text, no tags at all");+ expect(scan.arollVideoCount).toBe(0);+ expect(scan.heygenVideoCount).toBe(0);+ expect(scan.byTag).toEqual({});+ expect(scan.total).toBe(0);});});@@ -2193,6 +2259,9 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {expect(await resolveCompositionElementCount(null, "<div><span></span></div>")).toEqual({count: 2,source: "static",+ byTag: { div: 1, span: 1 },+ arollVideoCount: 0,+ heygenVideoCount: 0,});});@@ -2201,6 +2270,9 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {expect(await resolveCompositionElementCount(session, "<div></div>")).toEqual({count: 1,source: "static",+ byTag: { div: 1 },+ arollVideoCount: 0,+ heygenVideoCount: 0,});});@@ -2216,6 +2288,9 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {expect(await resolveCompositionElementCount(session, "<div><span></span></div>")).toEqual({count: 2,source: "static",+ byTag: { div: 1, span: 1 },+ arollVideoCount: 0,+ heygenVideoCount: 0,});});@@ -2224,8 +2299,19 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {expect(await resolveCompositionElementCount(session, "<div></div>")).toEqual({count: 1,source: "static",+ byTag: { div: 1 },+ arollVideoCount: 0,+ heygenVideoCount: 0,});});++ it("omits byTag/arollVideoCount on the live path — that path never runs the static scan", async () => {+ const session = { isInitialized: true, page: { evaluate: async () => 40001 } };+ const result = await resolveCompositionElementCount(session, "<div><span></span></div>");+ expect(result).not.toHaveProperty("byTag");+ expect(result).not.toHaveProperty("arollVideoCount");+ expect(result).not.toHaveProperty("heygenVideoCount");+ });});describe("envInt", () => {diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.tsindex 9855f58540..5c47c093e1 100644--- a/packages/producer/src/services/renderOrchestrator.ts+++ b/packages/producer/src/services/renderOrchestrator.ts@@ -513,6 +513,12 @@ export interface RenderPerfSummary {compositionElementCount?: number;/** Rough compiled-composition element-count provenance: "live" (probe DOM) | "static" (source scan, not trusted to open the band). */compositionElementCountSource?: "live" | "static";+ /** Per-tag breakdown of the same static scan behind compositionElementCount, capped at MAX_REPORTED_ELEMENT_TAGS + an "other" bucket. Only set when the source above is "static" — the live path never runs this scan. */+ compositionElementTags?: Readonly<Record<string, number>>;+ /** `<video data-aroll="true">` elements from the same static scan. Only set when compositionElementCountSource is "static". */+ arollVideoCount?: number;+ /** `<video data-media-source="heygen">` elements from the same static scan. Only set when compositionElementCountSource is "static". */+ heygenVideoCount?: number;/** Short-comp band attribution: "applied" | "skipped_elements" | "unmeasured"; unset when the frame count made the band irrelevant. */shortBand?: "applied" | "skipped_elements" | "unmeasured";/** DE parallel-router outcome: "routed" (fired, held), "reverted" (fired, self-verify retry rolled back), "none". Mutually exclusive with workerInversion. */@@ -1392,7 +1398,23 @@ export function envInt(name: string, fallback: number): number {}/**- * Rough element count for compiled composition HTML.+ * `scanElementTags`'s per-tag breakdown, capped so a pathological composition+ * with thousands of distinct tag names can't inflate the telemetry payload:+ * the top `MAX_REPORTED_ELEMENT_TAGS` tags by count survive as named keys,+ * everything past the cap folds into `other`. `total` is unaffected by the+ * cap — it is the sum of every match, capped or not.+ */+export interface ElementTagScan {+ total: number;+ byTag: Readonly<Record<string, number>>;+ arollVideoCount: number;+ heygenVideoCount: number;+}++const MAX_REPORTED_ELEMENT_TAGS = 50;++/**+ * Rough element count (and per-tag breakdown) for compiled composition HTML.** Deliberately a string scan and not a `parseHTML` + `querySelectorAll` (the* `countAuthoredTimedClips` approach): this runs on EVERY render before the@@ -1422,6 +1444,10 @@ export function envInt(name: string, fallback: number): number {* literal closing marker (`</`, a void name at a word boundary, or `/>`), so* ordinary JS comparisons and divisions don't qualify — verified by test.*+ * `byTag`/`arollVideoCount`/`heygenVideoCount` derive from the SAME matched set and the SAME+ * script/style-stripped markup as `total` — one scan feeds every property+ * this function returns, so none of them can drift apart from each other.+ ** FALLBACK ONLY as of the live-DOM fix below — a string scan of the SOURCE* markup cannot see elements a composition's own script creates at runtime* (`document.createElement`), which is an unbounded undercount no regex can@@ -1430,7 +1456,7 @@ export function envInt(name: string, fallback: number): number {* `resolveCompositionElementCount` prefers the initialized probe session's* live count and uses this only when no such session exists.*/-export function countElementTags(html: string): number {+export function scanElementTags(html: string): ElementTagScan {// Strip inline <script>/<style> bodies BEFORE matching. Every alternation// below can fire on ordinary JS text — `const html = "</div>"` or a// template literal building `</span>` inflates the count once per@@ -1451,10 +1477,40 @@ export function countElementTags(html: string): number {previous = markup;markup = markup.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, "");}- const matches = markup.match(- /<\/[a-zA-Z]|<(?:img|br|hr|input|source|track|area|base|col|embed|link|meta|param|wbr)\b|<[a-zA-Z][-a-zA-Z0-9]*\b[^>]*\/>/gi,+ let total = 0;+ const counts = new Map<string, number>();+ for (const m of markup.matchAll(+ /<\/([a-zA-Z][-a-zA-Z0-9]*)|<(img|br|hr|input|source|track|area|base|col|embed|link|meta|param|wbr)\b|<([a-zA-Z][-a-zA-Z0-9]*)\b[^>]*\/>/gi,+ )) {+ total++;+ const tag = (m[1] ?? m[2] ?? m[3] ?? "").toLowerCase();+ counts.set(tag, (counts.get(tag) ?? 0) + 1);+ }+ const ranked = [...counts.entries()].sort((a, b) => b[1] - a[1]);+ const byTag: Record<string, number> = Object.fromEntries(+ ranked.slice(0, MAX_REPORTED_ELEMENT_TAGS),);- return matches === null ? 0 : matches.length;+ const otherCount = ranked+ .slice(MAX_REPORTED_ELEMENT_TAGS)+ .reduce((sum, [, count]) => sum + count, 0);+ // `+=`, not `=`: a real (if exotic) tag literally named "other" could+ // already occupy this key from the top-N slice above — adding preserves+ // sum(byTag) === total in every case; overwriting would silently drop it.+ if (otherCount > 0) byTag.other = (byTag.other ?? 0) + otherCount;+ // `data-aroll="true"` is stamped on any media element type the composition+ // generator emits (video/img/audio — see hyperframes.ts's isMediaElement+ // gate), but this count is scoped to <video> only, matching its name: a-roll+ // is a video-editing term for primary-take footage, and every real usage in+ // this codebase's fixtures stamps it on video elements.+ const arollVideoCount =+ markup.match(/<video\b[^>]*\bdata-aroll=["']true["'][^>]*>/gi)?.length ?? 0;+ // `data-media-source="heygen"` is the media-use skill's own provenance+ // stamp (see resolve.md), written only when the mounted video's ledger+ // record traces to the "heygen.video" provider — never any other provider+ // or value, so a plain presence check is exact, not a substring guess.+ const heygenVideoCount =+ markup.match(/<video\b[^>]*\bdata-media-source=["']heygen["'][^>]*>/gi)?.length ?? 0;+ return { total, byTag, arollVideoCount, heygenVideoCount };}/**@@ -1466,7 +1522,7 @@ export function countElementTags(html: string): number {* caption-word-span pattern above builds thousands of nodes from two source* tags).*- * `static` — the `countElementTags` fallback. Emitted for diagnostics, but+ * `static` — the `scanElementTags` fallback. Emitted for diagnostics, but* NOT trusted to open the band: the probe is conditional (see* `probeStage.ts`'s `needsBrowser` — only unknown duration, unresolved* compositions, or specific media cases launch one), so a known-duration,@@ -1482,7 +1538,13 @@ export function countElementTags(html: string): number {export async function resolveCompositionElementCount(probeSession: Pick<CaptureSession, "isInitialized" | "page"> | null,html: string,-): Promise<{ count: number; source: "live" | "static" }> {+): Promise<{+ count: number;+ source: "live" | "static";+ byTag?: Readonly<Record<string, number>>;+ arollVideoCount?: number;+ heygenVideoCount?: number;+}> {if (probeSession?.isInitialized) {try {const liveCount = await probeSession.page.evaluate(@@ -1499,7 +1561,17 @@ export async function resolveCompositionElementCount(// render on a routing-gate measurement.}}- return { count: countElementTags(html), source: "static" };+ // byTag/arollVideoCount/heygenVideoCount are static-only: the live path+ // measures a real DOM node count and never runs this string scan, so it+ // has nothing to report.+ const scan = scanElementTags(html);+ return {+ count: scan.total,+ source: "static",+ byTag: scan.byTag,+ arollVideoCount: scan.arollVideoCount,+ heygenVideoCount: scan.heygenVideoCount,+ };}/**@@ -2932,8 +3004,13 @@ async function executeRenderPipeline(input: {// compositions, or specific media cases), so a known-duration media-free// comp that builds its DOM in script has no live count available and the// static scan reads it as tiny. Only a `live` count may open the band.- const { count: compositionElementCount, source: compositionElementCountSource } =- await resolveCompositionElementCount(probeSession, compiled.html);+ const {+ count: compositionElementCount,+ source: compositionElementCountSource,+ byTag: compositionElementTags,+ arollVideoCount,+ heygenVideoCount,+ } = await resolveCompositionElementCount(probeSession, compiled.html);// HF_DE_SHORT_MAX_ELEMENTS=0 is the documented kill switch (symmetric// with HF_DE_SHORT_MIN_FRAMES=0, which disables via the predicate's own// minFrames > 0 guard). Gated explicitly here too — without it, a fired@@ -3276,6 +3353,9 @@ async function executeRenderPipeline(input: {// perf shift can be split into "the new band did it" vs "unchanged".compositionElementCount,compositionElementCountSource,+ compositionElementTags,+ arollVideoCount,+ heygenVideoCount,deShortBand,// Same rationale as the counters above: carried on live capture// observability, not only the success-path perfSummary, so a crash /@@ -4186,6 +4266,9 @@ async function executeRenderPipeline(input: {preInversionWorkers: deWorkerInversion ? preRoutingWorkerCount : undefined,compositionElementCount,compositionElementCountSource,+ compositionElementTags,+ arollVideoCount,+ heygenVideoCount,shortBand: deShortBand,parallelRouter: deParallelRouter,preRouterWorkers: deParallelRouter ? preRoutingWorkerCount : undefined,diff --git a/skills-manifest.json b/skills-manifest.jsonindex e411541e93..6f3d7d7232 100644--- a/skills-manifest.json+++ b/skills-manifest.json@@ -50,7 +50,7 @@"files": 12},"media-use": {- "hash": "08a544dfaca9e846",+ "hash": "4531919cdbda573e","files": 158},"motion-graphics": {diff --git a/skills/media-use/references/resolve.md b/skills/media-use/references/resolve.mdindex 61c13cb32e..091483f4ad 100644--- a/skills/media-use/references/resolve.md+++ b/skills/media-use/references/resolve.md@@ -105,6 +105,17 @@ The deterministic floor still runs automatically: an identical (case/whitespace-Steps 1 and 3 are the **deterministic floor**: they only auto-reuse an exact-normalized match, never a fuzzy one. Semantic reuse ("close enough") is the agent's explicit call via [Reuse before you resolve](#reuse-before-you-resolve) — it never happens automatically. The agent gets back **one line**; candidates, scores, provenance stay on disk.+## Stamping provenance when mounting a resolved video++`resolve` never writes composition HTML itself — mounting a `<video>` element+into a composition is always the agent's own edit. When the mounted video's+manifest record has `provenance.provider === "heygen.video"` (check+`.media/manifest.jsonl` or the one-line resolve output for the provider name),+add `data-media-source="heygen"` to that `<video>` tag. Leave the attribute off+entirely for every other provider (`ltx.local`, an adopted/local file, etc.) —+this is not a general provider taxonomy, just the one signal render telemetry+tracks today.+## Adopt existing projectsMost HyperFrames projects already have assets in `assets/`. media-use adopts them: