editorbrain 0.42.1 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // packages/cli/src/style-assets.ts
4
- import { posix } from "node:path";
3
+ // packages/cli/src/production-output.ts
4
+ import { constants as constants2 } from "node:fs";
5
+ import { mkdir as mkdir2, open as open2 } from "node:fs/promises";
6
+ import { dirname as dirname2 } from "node:path";
5
7
 
6
8
  // packages/core/src/style-authoring.ts
7
9
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
@@ -14,7 +16,8 @@ var forbiddenText = /(?:\b[a-z][a-z0-9+.-]*:\/\/|\b(?:data|file|mailto):|\b(?:au
14
16
  function safeStyleResourcePath(path) {
15
17
  if (typeof path !== "string" || !path || path.length > 400 || path !== path.trim() || /[\\\x00-\x1f\x7f%:?#]/.test(path) || path.startsWith("/") || path.startsWith("~")) throw new Error("Resource path must be a safe workspace-relative path");
16
18
  const parts = path.split("/");
17
- if (parts.some((part) => !part || part === "." || part === ".." || part.length > 100 || /[. ]$/.test(part) || ["__proto__", "prototype", "constructor"].includes(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw new Error("Unsafe or nonportable resource path segment");
19
+ const invalid7 = parts.filter((part) => !part || part === "." || part === ".." || part.length > 100 || /[. ]$/.test(part) || ["__proto__", "prototype", "constructor"].includes(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part));
20
+ if (invalid7.length) throw new Error(`Unsafe or nonportable resource path segment in ${JSON.stringify(path)}: ${invalid7.map((p) => JSON.stringify(p)).join(", ")}. Use relative segments of 1\u2013100 characters without traversal, reserved device names or trailing dots/spaces.`);
18
21
  if (parts.some((part) => /^\.env(?:\.|$)/i.test(part) || /^(?:\.?credentials|secrets?|service[-_]account)(?:\.|$)/i.test(part) || [".git", ".ssh", ".aws", ".gnupg", ".sync.json", "id_rsa", "id_ed25519"].includes(part.toLowerCase()))) throw new Error("Credential and private configuration paths cannot be style resources");
19
22
  return path;
20
23
  }
@@ -229,7 +232,7 @@ function styleReuseIssues(name, value, expectedId) {
229
232
  const fields = (v, allowed, label) => {
230
233
  if (obj(v) && Object.keys(v).some((k) => !allowed.includes(k))) add(`${label} has unsupported fields; store only the documented contract, never credentials.`);
231
234
  };
232
- const top = { "techniques.json": ["techniques"], "media-style.json": ["status", "model", "referenceOrder", "promptTemplate", "variables", "reviewBeforeAnimation", "animation"], "captions.json": ["enabled", "font", "activeBox", "position", "forbiddenZones", "hideDuringCrossings", "tokenBindings"], "components.json": ["components"] };
235
+ const top = { "techniques.json": ["techniques"], "media-style.json": ["status", "model", "referenceOrder", "promptTemplate", "variables", "reviewBeforeAnimation", "animation"], "captions.json": ["mode", "enabled", "font", "activeBox", "position", "forbiddenZones", "hideDuringCrossings", "tokenBindings"], "components.json": ["components"] };
233
236
  fields(value, ["schemaVersion", "id", ...top[name]], name);
234
237
  if (name === "techniques.json") {
235
238
  if (!Array.isArray(value.techniques) || value.techniques.length > 100) add("techniques must contain at most 100 entries.");
@@ -259,6 +262,7 @@ function styleReuseIssues(name, value, expectedId) {
259
262
  }
260
263
  if (name === "captions.json") {
261
264
  const f = value.font, b = value.activeBox, p = value.position, z = value.forbiddenZones;
265
+ if (value.mode !== void 0 && !["phrase", "karaoke"].includes(String(value.mode))) add("Caption mode must be phrase or karaoke. Karaoke needs explicit word timings in the cues.");
262
266
  fields(f, ["family", "weight", "size", "color", "resourceId"], "Caption font");
263
267
  fields(b, ["color", "padding"], "Caption activeBox");
264
268
  fields(p, ["x", "y"], "Caption position");
@@ -308,12 +312,22 @@ function validateCaptionCues(value) {
308
312
  for (const item of value) {
309
313
  if (!item || typeof item !== "object" || !Number.isFinite(item.start) || !Number.isFinite(item.end) || item.start < end3 || item.end <= item.start || item.end > 86400 || typeof item.text !== "string" || !item.text.trim() || item.text.length > 500 || item.active !== void 0 && typeof item.active !== "boolean" || item.crossing !== void 0 && typeof item.crossing !== "boolean") throw new Error("Each caption cue needs ordered nonoverlapping start/end seconds, text (1\u2013500 chars), optional active and crossing booleans.");
310
314
  end3 = item.end;
315
+ if (item.words !== void 0) {
316
+ if (!Array.isArray(item.words) || !item.words.length || item.words.length > 100) throw new Error("Caption words need 1\u2013100 word timings.");
317
+ let wordEnd = item.start;
318
+ for (const word of item.words) {
319
+ if (!word || typeof word.text !== "string" || !word.text.trim() || word.text.length > 500 || !Number.isFinite(word.start) || !Number.isFinite(word.end) || word.start < wordEnd || word.end <= word.start || word.end > item.end) throw new Error("Caption word timings must be ordered, nonoverlapping and inside their cue.");
320
+ wordEnd = word.end;
321
+ }
322
+ if (item.words.map((w) => w.text.trim()).join(" ") !== item.text.trim().replace(/\s+/g, " ")) throw new Error("Caption words must reproduce the cue text in order.");
323
+ }
311
324
  }
312
325
  return value;
313
326
  }
314
327
  function captionLayer(preset, cues, width, height, fontDataUrl) {
315
328
  validateStyleReuse("captions.json", preset, preset.id);
316
329
  validateCaptionCues(cues);
330
+ if (preset.mode === "karaoke" && cues.some((c) => !c.words?.length)) throw new Error("Karaoke requires words with measured start/end seconds in every cue; timings are never estimated.");
317
331
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 16 || height < 16 || width > 8192 || height > 8192) throw new Error("Invalid caption canvas dimensions.");
318
332
  if (fontDataUrl && !/^data:font\/(?:woff2?|ttf|otf);base64,[A-Za-z0-9+/]+=*$/.test(fontDataUrl)) throw new Error("Invalid embedded font.");
319
333
  const data = JSON.stringify({ preset, cues, width, height, fontDataUrl }).replace(/[<>&\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
@@ -325,7 +339,16 @@ window.renderAt=async function(seconds){
325
339
  await fontReady;await document.fonts.ready;el.hidden=true;
326
340
  const cue=data.cues.find(c=>seconds>=c.start&&seconds<c.end);
327
341
  if(!p.enabled||!cue||(p.hideDuringCrossings&&cue.crossing))return {visible:false};
328
- el.textContent=cue.text;el.style.background=cue.active?p.activeBox.color:'transparent';el.style.padding=cue.active?p.activeBox.padding+'px':'0';el.hidden=false;
342
+ el.replaceChildren();el.style.background='transparent';el.style.padding='0';
343
+ if(p.mode==='karaoke'){
344
+ for(const [index,word]of cue.words.entries()){
345
+ if(index)el.append(document.createTextNode(' '));const span=document.createElement('span');span.textContent=word.text;
346
+ span.style.padding='0 '+p.activeBox.padding+'px';span.style.boxDecorationBreak='clone';
347
+ if(seconds>=word.start&&seconds<word.end){span.dataset.active='true';span.style.background=p.activeBox.color;}
348
+ el.append(span);
349
+ }
350
+ }else{el.textContent=cue.text;el.style.background=cue.active?p.activeBox.color:'transparent';el.style.padding=cue.active?p.activeBox.padding+'px':'0';}
351
+ el.hidden=false;
329
352
  const r=el.getBoundingClientRect();const collision=p.forbiddenZones.some(z=>r.left<(z.x+z.width)*data.width&&r.right>z.x*data.width&&r.top<(z.y+z.height)*data.height&&r.bottom>z.y*data.height);
330
353
  if(collision||r.left<0||r.top<0||r.right>data.width||r.bottom>data.height){el.hidden=true;return {visible:false,reason:'forbidden_zone_or_overflow'};}
331
354
  return {visible:true,text:cue.text};
@@ -529,19 +552,19 @@ function recoveryHint(help) {
529
552
  // packages/core/src/tool-preferences.ts
530
553
  var toolLanguages = ["project", "es", "en", "pt", "fr", "de", "it"];
531
554
  function validateToolPreferences(input) {
532
- const obj2 = (value2, keys2) => {
555
+ const obj3 = (value2, keys2) => {
533
556
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2) || Object.keys(value2).some((k) => !keys2.includes(k))) throw new Error("Invalid AI tool preference fields.");
534
557
  return value2;
535
558
  };
536
559
  const choice = (v, values) => {
537
560
  if (!values.includes(v)) throw new Error("Unsupported AI tool preference.");
538
561
  };
539
- const value = obj2(input, ["schemaVersion", "transcription", "images", "narration", "music"]);
562
+ const value = obj3(input, ["schemaVersion", "transcription", "images", "narration", "music"]);
540
563
  if (value.schemaVersion !== 1) throw new Error("Tool preferences schemaVersion must be 1.");
541
564
  for (const key of ["transcription", "images", "narration", "music"]) {
542
565
  if (value[key] === void 0) continue;
543
566
  const fields = { transcription: ["provider", "language"], images: ["provider", "quality", "resolution", "aspectRatio"], narration: ["provider", "language"], music: ["provider", "durationSeconds", "character"] }[key];
544
- const section = obj2(value[key], fields);
567
+ const section = obj3(value[key], fields);
545
568
  if (fields.some((field) => section[field] === void 0)) throw new Error("Incomplete AI tool preferences.");
546
569
  const providers = { transcription: ["editorbrain", "assemblyai"], images: ["editorbrain", "higgsfield", "openai-images"], narration: ["editorbrain", "elevenlabs"], music: ["editorbrain", "suno", "elevenlabs"] }[key];
547
570
  choice(section.provider, providers);
@@ -1623,8 +1646,8 @@ function text3(value, name, max = 200) {
1623
1646
  function validateAudioLoudnessTarget(value) {
1624
1647
  const input = record4(value, "loudness", ["targetIntegratedLufs", "toleranceLu", "maxTruePeakDbtp"]);
1625
1648
  for (const field of ["targetIntegratedLufs", "toleranceLu", "maxTruePeakDbtp"]) {
1626
- const number2 = input[field];
1627
- if (typeof number2 !== "number" || !Number.isFinite(number2) || (field === "toleranceLu" ? number2 < 0 || number2 > 150 : number2 < -150 || number2 > 24)) throw new Error(`loudness.${field} must be a finite measurement target within the supported range.`);
1649
+ const number3 = input[field];
1650
+ if (typeof number3 !== "number" || !Number.isFinite(number3) || (field === "toleranceLu" ? number3 < 0 || number3 > 150 : number3 < -150 || number3 > 24)) throw new Error(`loudness.${field} must be a finite measurement target within the supported range.`);
1628
1651
  }
1629
1652
  return { targetIntegratedLufs: input.targetIntegratedLufs, toleranceLu: input.toleranceLu, maxTruePeakDbtp: input.maxTruePeakDbtp };
1630
1653
  }
@@ -181621,12 +181644,12 @@ var SOCIAL_SAFE_PROFILES = {
181621
181644
  reels: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 },
181622
181645
  shorts: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 }
181623
181646
  };
181624
- function validateVisualReview(value, hash8, duration, width, height) {
181647
+ function validateVisualReview(value, hash9, duration, width, height) {
181625
181648
  const v = value;
181626
181649
  const fail3 = () => {
181627
181650
  throw new Error("Invalid visual profile: use the exact artifact hash, output-clock seconds and output-pixel boxes.");
181628
181651
  };
181629
- if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash8 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail3();
181652
+ if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash9 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail3();
181630
181653
  if (Object.keys(v).some((k) => !["schemaVersion", "artifactSha256", "platform", "holds", "geometry"].includes(k))) fail3();
181631
181654
  if (v.platform !== void 0 && !Object.hasOwn(SOCIAL_SAFE_PROFILES, v.platform)) fail3();
181632
181655
  if (v.holds !== void 0 && (!Array.isArray(v.holds) || v.holds.length > 1e3)) fail3();
@@ -182528,20 +182551,6 @@ function canonicalFiles(files) {
182528
182551
  return result2;
182529
182552
  }
182530
182553
 
182531
- // packages/cli/src/style-assets.ts
182532
- function styleAssetPath(id3, source2) {
182533
- assertIdentifier(id3);
182534
- if (!/^[a-f0-9]{64}$/.test(source2.assetId)) throw new Error("Invalid asset hash");
182535
- const ext = source2.fileName ? posix.extname(source2.fileName).toLowerCase() : ".bin";
182536
- if (!/^\.[a-z0-9]{1,10}$/.test(ext)) throw new Error("Invalid asset extension");
182537
- return `production-assets/styles/${id3}/${source2.assetId}${ext}`;
182538
- }
182539
-
182540
- // packages/cli/src/style-sync.ts
182541
- import { createHash as createHash3 } from "node:crypto";
182542
- import { lstat as lstat5 } from "node:fs/promises";
182543
- import { posix as posix3 } from "node:path";
182544
-
182545
182554
  // packages/cli/src/io.ts
182546
182555
  import { constants } from "node:fs";
182547
182556
  import { lstat, mkdir, open, readdir, realpath, rename, unlink, link } from "node:fs/promises";
@@ -182657,9 +182666,6 @@ async function readProjectWorkspace(root, projectId) {
182657
182666
  return canonicalFiles(files);
182658
182667
  }
182659
182668
 
182660
- // packages/cli/src/client.ts
182661
- import { setTimeout as delay } from "node:timers/promises";
182662
-
182663
182669
  // packages/cli/src/errors.ts
182664
182670
  var CliError = class extends Error {
182665
182671
  constructor(code, message, hint, retryable = false, details = {}) {
@@ -182679,10 +182685,784 @@ function errorOutput(error) {
182679
182685
  if (error instanceof ValidationError) return { error: "Workspace validation failed.", code: "VALIDATION_FAILED", retryable: false, hint: "Correct the reported documents before retrying.", issues: error.issues };
182680
182686
  const message = error instanceof Error ? error.message : "Unknown error";
182681
182687
  const safe = message.replace(/\b(?:eh_[a-f0-9]{64}|npm_[A-Za-z0-9]+)\b/g, "[REDACTED]").replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]").replace(/(https?:\/\/[^\s?]+)\?[^\s]*/g, "$1?[REDACTED]");
182688
+ const errno = error && typeof error === "object" && "code" in error ? String(error.code) : "";
182689
+ if (["ENOENT", "EACCES", "ENOSPC", "EEXIST"].includes(errno)) return { error: safe, code: errno, retryable: false, hint: { ENOENT: "Check the named input path and --dir. Inputs must exist in this workspace.", EACCES: "Check permissions on the named path; do not retry with elevated privileges automatically.", ENOSPC: "Run editorbrain clean --project ID to inspect disk use. Preserve sources and final renders.", EEXIST: "The output already exists. Select a new output path; existing work is preserved." }[errno] };
182690
+ if (/Path escapes workspace|Symlinks are not allowed|nonportable resource path/.test(safe)) return { error: safe, code: "UNSAFE_LOCAL_PATH", retryable: false, hint: "Use a real workspace-relative file inside --dir; do not weaken path guards." };
182682
182691
  return { error: safe, code: "COMMAND_FAILED", retryable: false, hint: "Read the command help and run editorbrain doctor. Do not retry writes blindly." };
182683
182692
  }
182684
182693
 
182694
+ // packages/cli/src/production-output.ts
182695
+ async function productionOutputPath(root, relativePath) {
182696
+ if (!relativePath.startsWith(".editorbrain-local/") || relativePath.split(/[\\/]/).some((p) => !p || p === ".." || p === ".") || /[\\\x00-\x1f\x7f]/.test(relativePath)) {
182697
+ throw new CliError("LOCAL_OUTPUT_REQUIRED", "Production output must be inside .editorbrain-local/.", "Use --out .editorbrain-local/<project>/inventory.json, or omit --out for JSON stdout. These reports are not synced.");
182698
+ }
182699
+ return checkedPath(root, relativePath, false);
182700
+ }
182701
+ async function prepareSampleDirectory(root, path) {
182702
+ const target = await productionOutputPath(root, path);
182703
+ await mkdir2(dirname2(target), { recursive: true });
182704
+ await productionOutputPath(root, path);
182705
+ return target;
182706
+ }
182707
+ async function readProductionJson(root, path) {
182708
+ const target = await checkedPath(root, path, false);
182709
+ const handle = await open2(target, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
182710
+ try {
182711
+ const stat = await handle.stat();
182712
+ if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new CliError("INVALID_REPORT", "Expected a regular JSON file of at most 16 MiB.", "Select a local inventory, plan or check profile.");
182713
+ return JSON.parse(await handle.readFile("utf8"));
182714
+ } finally {
182715
+ await handle.close();
182716
+ }
182717
+ }
182718
+ async function saveProductionReport(root, path, report) {
182719
+ const target = await productionOutputPath(root, path);
182720
+ if (!path.endsWith(".json")) throw new CliError("INVALID_ARGUMENT", "Report output needs a .json extension.", "Use a new path under .editorbrain-local/.");
182721
+ await atomicWrite(root, path, stableJson(report), { document: false, overwrite: false, mode: 384 });
182722
+ return target;
182723
+ }
182724
+ function summarizeProductionReport(value) {
182725
+ const r = value;
182726
+ const base = { schemaVersion: r.schemaVersion, kind: r.kind, summary: true, mediaUploaded: false, quality: "not_assessed" };
182727
+ if (r.kind === "editorbrain.media-inventory") return {
182728
+ ...base,
182729
+ complete: r.complete,
182730
+ contentReviewed: false,
182731
+ counts: { assets: r.assets.length, failures: r.failures.length, skipped: r.skipped.length },
182732
+ assets: r.assets.slice(0, 8),
182733
+ failures: r.failures.slice(0, 5),
182734
+ omitted: { assets: Math.max(0, r.assets.length - 8), failures: Math.max(0, r.failures.length - 5), skipped: r.skipped.length },
182735
+ next: "Inspect selected source content. Use media sample for specific frames. Read the saved report or rerun with --details for omitted metadata; no content was reviewed automatically."
182736
+ };
182737
+ if (r.kind === "editorbrain.media-samples") return { ...base, sourceSha256: r.source.sha256, frames: r.frames, contentReviewed: false, next: "View these frames to inspect composition. They do not prove motion or sound." };
182738
+ if (r.kind === "editorbrain.production-plan-check") return {
182739
+ ...base,
182740
+ valid: r.valid,
182741
+ inventoryComplete: r.inventoryComplete,
182742
+ observations: r.observations,
182743
+ sourceFilesReverified: false,
182744
+ counts: { sources: r.coverage.length, findings: r.findings.length, repeatedPairs: r.repeatedPairs ?? 0 },
182745
+ findings: [...r.findings].sort((a, b) => ({ error: 0, warning: 1, info: 2 })[a.severity] - { error: 0, warning: 1, info: 2 }[b.severity]).slice(0, 8),
182746
+ omittedFindings: Math.max(0, r.findings.length - 8),
182747
+ next: "Review source reuse and inspection gaps in the saved report. Observations are agent-declared, not independently certified."
182748
+ };
182749
+ if (r.kind === "editorbrain.render-check") return {
182750
+ ...base,
182751
+ complete: r.complete,
182752
+ technicalStatus: r.technicalStatus,
182753
+ file: r.file,
182754
+ checks: r.checks,
182755
+ findings: r.findings.slice(0, 8),
182756
+ findingsSummary: r.findingsSummary,
182757
+ omittedFindings: Math.max(0, r.findings.length - 8),
182758
+ next: "Reconcile technical candidates with the brief; inspect the actual video/audio. Technical checks do not assess narrative, aesthetics or SFX audibility."
182759
+ };
182760
+ if (r.kind === "editorbrain.media-source-search") return {
182761
+ ...base,
182762
+ complete: r.complete,
182763
+ results: r.results.slice(0, 5).map((item) => ({ provider: item.provider, id: item.id.slice(0, 180), title: item.title.slice(0, 180), sourceUrl: item.sourceUrl.length <= 1500 ? item.sourceUrl : null, author: item.author?.slice(0, 120) ?? null, license: { id: item.license.id, reason: item.license.reason, url: item.license.url && item.license.url.length <= 500 ? item.license.url : null }, contentReviewed: false, rightsVerified: false })),
182764
+ metadataAbbreviated: true,
182765
+ failures: r.failures.slice(0, 5),
182766
+ counts: r.counts,
182767
+ omitted: { results: Math.max(0, r.results.length - 5), failures: Math.max(0, r.failures.length - 5) },
182768
+ searchExhaustive: false,
182769
+ rightsVerified: false,
182770
+ next: "Inspect relevant source pages and media. These archives supplement web image/video search; empty results do not prove absence on the internet."
182771
+ };
182772
+ if (r.kind === "editorbrain.evidence-check") return {
182773
+ ...base,
182774
+ valid: r.valid,
182775
+ inventoryComplete: r.inventoryComplete,
182776
+ observations: r.observations,
182777
+ sourceFilesReverified: false,
182778
+ factualTruth: "not_assessed",
182779
+ reuseRights: "not_assessed",
182780
+ findings: r.findings.slice(0, 8),
182781
+ omitted: { findings: Math.max(0, r.findings.length - 8) }
182782
+ };
182783
+ if (r.kind === "editorbrain.audio-check") return {
182784
+ ...base,
182785
+ complete: r.complete,
182786
+ technicalStatus: r.technicalStatus,
182787
+ file: r.file,
182788
+ fileStable: r.fileStable,
182789
+ coverage: r.coverage,
182790
+ measurements: r.measurements.slice(0, 8),
182791
+ errorCode: r.errorCode,
182792
+ creativeQuality: r.creativeQuality,
182793
+ omitted: { measurements: Math.max(0, r.measurements.length - 8) },
182794
+ next: "Measurements describe this exact file. Listen for intelligibility, pronunciation, SFX and sync when the modality is available."
182795
+ };
182796
+ if (r.kind === "editorbrain.motion-review") return {
182797
+ ...base,
182798
+ samples: r.samples ? { frameCount: r.samples.frameCount, fps: r.samples.fps, radiusFrames: r.samples.radiusFrames, samples: r.samples.samples.slice(0, 12), omittedSamples: Math.max(0, r.samples.samples.length - 12) } : null,
182799
+ geometryReviews: r.geometryReviews.slice(0, 3).map((g) => ({ scope: g.scope, status: g.status, candidates: g.candidates.slice(0, 8), omittedCandidates: Math.max(0, g.candidates.length - 8), checks: g.checks })),
182800
+ omittedGeometryReviews: Math.max(0, r.geometryReviews.length - 3),
182801
+ next: "This plans samples and checks declared boxes only. Render/view those frames; read saved details for omitted candidates and intentional overlaps."
182802
+ };
182803
+ throw new CliError("INVALID_REPORT", "Unknown production report kind.", "Use media inventory/sample or production check/plan-check.");
182804
+ }
182805
+
182806
+ // packages/cli/src/media-runtime.ts
182807
+ import { spawn } from "node:child_process";
182808
+ import { createHash } from "node:crypto";
182809
+ import { constants as constants3 } from "node:fs";
182810
+ import { lstat as lstat2, open as open3, realpath as realpath2 } from "node:fs/promises";
182811
+ import { dirname as dirname3, extname, parse, resolve as resolve2 } from "node:path";
182812
+ var MediaToolError = class extends CliError {
182813
+ constructor(code, message) {
182814
+ super(code, message, code === "MEDIA_TOOL_NOT_FOUND" ? "Install FFmpeg/FFprobe separately and make them available on PATH; no account or model is needed." : "Review the local input and reported limit. An incomplete check does not validate the media.");
182815
+ this.name = "MediaToolError";
182816
+ }
182817
+ };
182818
+ var SUPPORTED_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
182819
+ ".mp4",
182820
+ ".mov",
182821
+ ".m4v",
182822
+ ".mkv",
182823
+ ".webm",
182824
+ ".avi",
182825
+ ".mpg",
182826
+ ".mpeg",
182827
+ ".mts",
182828
+ ".m2ts",
182829
+ ".ts",
182830
+ ".ogv",
182831
+ ".wmv",
182832
+ ".wav",
182833
+ ".mp3",
182834
+ ".m4a",
182835
+ ".aac",
182836
+ ".flac",
182837
+ ".ogg",
182838
+ ".opus",
182839
+ ".aif",
182840
+ ".aiff",
182841
+ ".ac3",
182842
+ ".eac3",
182843
+ ".jpg",
182844
+ ".jpeg",
182845
+ ".png",
182846
+ ".webp",
182847
+ ".bmp",
182848
+ ".tif",
182849
+ ".tiff",
182850
+ ".gif",
182851
+ ".avif",
182852
+ ".heic",
182853
+ ".heif"
182854
+ ]);
182855
+ var PROTOCOLS = "file,pipe";
182856
+ var FORMATS = "mov,matroska,webm,avi,mpeg,mpegts,ogg,wav,flac,mp3,aac,aiff,ac3,eac3,asf,jpeg_pipe,png_pipe,webp_pipe,bmp_pipe,tiff_pipe,gif,heif,avif";
182857
+ var DEFAULT_TIMEOUT = 3e4;
182858
+ var DEFAULT_OUTPUT_LIMIT = 2 * 1024 * 1024;
182859
+ function resolveLocalMediaPath(value) {
182860
+ if (!value || value.includes("\0") || /[\r\n]/.test(value) || /^[a-z][a-z\d+.-]*:/i.test(value) && !(process.platform === "win32" && /^[a-z]:[\\/]/i.test(value)) || value.startsWith("\\\\")) {
182861
+ throw new MediaToolError("MEDIA_LOCAL_PATH_REQUIRED", "Provide a local filesystem path, not a URL, protocol or network share.");
182862
+ }
182863
+ return resolve2(value);
182864
+ }
182865
+ async function assertNoMediaSymlinks(value) {
182866
+ const path = resolveLocalMediaPath(value);
182867
+ let cursor = path;
182868
+ while (cursor !== parse(cursor).root) {
182869
+ const info = await lstat2(cursor);
182870
+ if (info.isSymbolicLink()) {
182871
+ const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath2(cursor) === `/private${cursor}`;
182872
+ if (!systemAlias) throw new MediaToolError("MEDIA_SYMLINK", "Symlink media paths are not followed. Use the original local path.");
182873
+ }
182874
+ cursor = dirname3(cursor);
182875
+ }
182876
+ return path;
182877
+ }
182878
+ async function assertLocalMediaFile(value) {
182879
+ const path = await assertNoMediaSymlinks(value);
182880
+ const info = await lstat2(path);
182881
+ if (!info.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
182882
+ if (!SUPPORTED_MEDIA_EXTENSIONS.has(extname(path).toLowerCase())) throw new MediaToolError("MEDIA_FORMAT_UNSUPPORTED", "This file extension is not supported for local media inspection.");
182883
+ return path;
182884
+ }
182885
+ function localInputArgs(path) {
182886
+ return ["-protocol_whitelist", PROTOCOLS, "-format_whitelist", FORMATS, "-i", resolveLocalMediaPath(path)];
182887
+ }
182888
+ async function runMediaTool(tool, args, options = {}) {
182889
+ if (tool !== "ffmpeg" && tool !== "ffprobe") throw new MediaToolError("MEDIA_TOOL_INVALID", "Unsupported media executable.");
182890
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
182891
+ const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_OUTPUT_LIMIT;
182892
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 6e4 || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > 16 * 1024 * 1024) {
182893
+ throw new MediaToolError("MEDIA_TOOL_LIMITS_INVALID", "Media runtime limits are outside the supported range.");
182894
+ }
182895
+ if (!Array.isArray(args) || args.length > 200 || args.some((arg) => typeof arg !== "string" || arg.length > 8192 || arg.includes("\0"))) {
182896
+ throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Invalid media tool arguments.");
182897
+ }
182898
+ for (let i = 0; i < args.length; i++) {
182899
+ const arg = args[i];
182900
+ if (/(?:^|[=,;\s])(?:https?|ftp|sftp|tcp|udp|rtsp|rtmp|smb|data|concat|subfile|crypto):/i.test(arg) || arg === "-safe" && args[i + 1] === "0" || arg === "-enable_drefs" && args[i + 1] !== "0") {
182901
+ throw new MediaToolError("MEDIA_REMOTE_INPUT_FORBIDDEN", "Only self-contained local media inputs are allowed.");
182902
+ }
182903
+ if (arg === "-protocol_whitelist" && args[i + 1] !== PROTOCOLS || arg === "-format_whitelist" && args[i + 1] !== FORMATS) {
182904
+ throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "The local media allowlists cannot be widened.");
182905
+ }
182906
+ if (arg === "-i") {
182907
+ await assertLocalMediaFile(args[i + 1] ?? "");
182908
+ if (args[i - 4] !== "-protocol_whitelist" || args[i - 3] !== PROTOCOLS || args[i - 2] !== "-format_whitelist" || args[i - 1] !== FORMATS) {
182909
+ throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Every media input must use localInputArgs.");
182910
+ }
182911
+ }
182912
+ }
182913
+ return new Promise((resolveResult, reject) => {
182914
+ const stdout = [], stderr = [];
182915
+ let size = 0, done = false;
182916
+ const child = spawn(tool, ["-hide_banner", ...tool === "ffmpeg" ? ["-nostdin"] : [], ...args], { shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
182917
+ const fail3 = (error) => {
182918
+ if (done) return;
182919
+ done = true;
182920
+ clearTimeout(timer);
182921
+ child.kill("SIGKILL");
182922
+ reject(error);
182923
+ };
182924
+ const timer = setTimeout(() => fail3(new MediaToolError("MEDIA_TOOL_TIMEOUT", "The local media check exceeded its time limit. No complete result is available.")), timeoutMs);
182925
+ const collect = (target) => (chunk) => {
182926
+ if (done) return;
182927
+ size += chunk.length;
182928
+ if (size > maxOutputBytes) return fail3(new MediaToolError("MEDIA_TOOL_OUTPUT_LIMIT", "The local media check exceeded its output limit. No complete result is available."));
182929
+ target.push(chunk);
182930
+ };
182931
+ child.stdout.on("data", collect(stdout));
182932
+ child.stderr.on("data", collect(stderr));
182933
+ child.on("error", (error) => fail3(new MediaToolError(error.code === "ENOENT" ? "MEDIA_TOOL_NOT_FOUND" : "MEDIA_TOOL_FAILED", error.code === "ENOENT" ? `${tool} is not installed or available on PATH. Install it separately to use local media checks.` : "The local media executable could not run.")));
182934
+ child.on("close", (code) => {
182935
+ if (done) return;
182936
+ done = true;
182937
+ clearTimeout(timer);
182938
+ if (code !== 0) return reject(new MediaToolError("MEDIA_TOOL_FAILED", "The local media tool could not inspect or decode this input. No complete result is available."));
182939
+ resolveResult({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
182940
+ });
182941
+ });
182942
+ }
182943
+ var finite2 = (value) => {
182944
+ if (typeof value !== "number" && typeof value !== "string" || value === "") return null;
182945
+ const n = Number(value);
182946
+ return Number.isFinite(n) ? n : null;
182947
+ };
182948
+ var nonnegative2 = (value) => {
182949
+ const n = finite2(value);
182950
+ return n !== null && n >= 0 ? n : null;
182951
+ };
182952
+ var positiveInteger = (value) => {
182953
+ const n = finite2(value);
182954
+ return n !== null && Number.isInteger(n) && n > 0 ? n : void 0;
182955
+ };
182956
+ var rate2 = (value) => {
182957
+ if (typeof value !== "string" || !/^\d+(?:\/\d+)?$/.test(value)) return null;
182958
+ const [n, d = "1"] = value.split("/");
182959
+ const result2 = Number(n) / Number(d);
182960
+ return Number.isFinite(result2) && result2 > 0 ? result2 : null;
182961
+ };
182962
+ var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
182963
+ function hasDisplayTransform(stream) {
182964
+ const rotate = stream.tags?.rotate;
182965
+ if (rotate !== void 0 && (!Number.isFinite(Number(rotate)) || Number(rotate) % 360 !== 0)) return true;
182966
+ const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : [];
182967
+ return sideData.some((data) => {
182968
+ if (!data || typeof data !== "object") return false;
182969
+ if (data.rotation !== void 0 && (!Number.isFinite(Number(data.rotation)) || Number(data.rotation) % 360 !== 0)) return true;
182970
+ if (data.displaymatrix === void 0) return data.side_data_type === "Display Matrix";
182971
+ if (typeof data.displaymatrix !== "string") return true;
182972
+ const values = data.displaymatrix.trim().split("\n").flatMap((line) => line.replace(/^[^:]*:/, "").trim().split(/\s+/).map(Number));
182973
+ const identity = [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824];
182974
+ return values.length !== 9 || values.some((value, index) => value !== identity[index]);
182975
+ });
182976
+ }
182977
+ async function probeLocalMedia(value) {
182978
+ const path = await assertLocalMediaFile(value);
182979
+ const handle = await open3(path, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
182980
+ try {
182981
+ const before = await handle.stat();
182982
+ if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
182983
+ const entries = "format=duration,start_time:stream=index,codec_type,codec_name,width,height,avg_frame_rate,sample_rate,channels,duration,color_transfer,sample_aspect_ratio,pix_fmt:stream_disposition=attached_pic:stream_side_data=side_data_type,rotation,displaymatrix:stream_tags=rotate";
182984
+ const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
182985
+ const hash9 = createHash("sha256");
182986
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash9.update(chunk);
182987
+ const after = await handle.stat();
182988
+ await assertNoMediaSymlinks(path);
182989
+ const current2 = await lstat2(path);
182990
+ if (!sameFile(before, after) || !sameFile(after, current2)) throw new MediaToolError("MEDIA_FILE_CHANGED", "The media file changed while it was being inspected. Retry with a stable source.");
182991
+ let raw;
182992
+ try {
182993
+ raw = JSON.parse(stdout);
182994
+ } catch {
182995
+ throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid metadata.");
182996
+ }
182997
+ if (!raw || !Array.isArray(raw.streams) || raw.streams.length > 256 || raw.streams.some((stream) => !stream || typeof stream !== "object" || Array.isArray(stream))) throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid or excessive stream metadata.");
182998
+ const streams = raw.streams.map((stream, offset) => {
182999
+ const type = typeof stream.codec_type === "string" && /^(video|audio|subtitle|data|attachment|unknown)$/.test(stream.codec_type) ? stream.codec_type : "unknown";
183000
+ const codec = typeof stream.codec_name === "string" && /^[a-zA-Z0-9_]{1,64}$/.test(stream.codec_name) ? stream.codec_name : null;
183001
+ const index = finite2(stream.index);
183002
+ return {
183003
+ index: index !== null && Number.isInteger(index) && index >= 0 ? index : offset,
183004
+ type,
183005
+ codec,
183006
+ durationSeconds: nonnegative2(stream.duration),
183007
+ ...type === "video" ? { displayTransformed: hasDisplayTransform(stream), width: positiveInteger(stream.width), height: positiveInteger(stream.height), fps: rate2(stream.avg_frame_rate), ...typeof stream.sample_aspect_ratio === "string" ? { sampleAspectRatio: stream.sample_aspect_ratio } : {}, ...typeof stream.pix_fmt === "string" ? { pixelFormat: stream.pix_fmt } : {}, ...typeof stream.color_transfer === "string" ? { colorTransfer: stream.color_transfer } : {}, attachedPicture: stream.disposition?.attached_pic === 1 } : {},
183008
+ ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
183009
+ };
183010
+ });
183011
+ return { path, sha256: hash9.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
183012
+ } finally {
183013
+ await handle.close();
183014
+ }
183015
+ }
183016
+
183017
+ // packages/cli/src/production-continuity-check.ts
183018
+ var obj2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
183019
+ var number2 = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
183020
+ var hash4 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
183021
+ function validateContinuityInput(value) {
183022
+ const issues = [];
183023
+ if (!obj2(value)) throw new CliError("INVALID_REVIEW_INPUT", "Review input must be an object.", "Use the documented continuity schema.");
183024
+ const add = (s) => issues.push(s);
183025
+ if (value.schemaVersion !== 1 || !hash4(value.artifactSha256)) add("schemaVersion: 1 and artifactSha256 (64 lowercase hex) are required.");
183026
+ if (Object.keys(value).some((k) => !["schemaVersion", "artifactSha256", "cuts", "transcript", "geometry"].includes(k))) add("Unexpected top-level review field.");
183027
+ if (!value.cuts && !value.geometry) add("Provide cuts + transcript and/or geometry.");
183028
+ if (value.cuts || value.transcript) {
183029
+ if (!obj2(value.cuts) || !hash4(value.cuts.sourceSha256) || !Array.isArray(value.cuts.parts) || value.cuts.parts.length < 1 || value.cuts.parts.length > 200) add("cuts requires sourceSha256 and 1\u2013200 parts.");
183030
+ else value.cuts.parts.forEach((p, i) => {
183031
+ if (!obj2(p) || !["source", "final"].every((k) => Array.isArray(p[k]) && p[k].length === 2 && p[k].every(number2) && p[k][1] > p[k][0])) add(`cuts.parts[${i}]: expected source:[start,end], final:[start,end] in seconds.`);
183032
+ else if (i && Math.abs(p.final[0] - value.cuts.parts[i - 1]?.final?.[1]) > 2e-3) add(`cuts.parts[${i}]: final intervals must be contiguous and ordered.`);
183033
+ });
183034
+ if (!obj2(value.transcript) || !hash4(value.transcript.sourceSha256) || value.transcript.sourceSha256 !== value.cuts?.sourceSha256 || !Array.isArray(value.transcript.words) || !value.transcript.words.length || value.transcript.words.length > 3e4) add("transcript requires matching sourceSha256 and 1\u201330000 source-timeline words.");
183035
+ else value.transcript.words.forEach((w, i) => {
183036
+ if (!obj2(w) || typeof w.text !== "string" || w.text.length > 500 || !number2(w.start) || !number2(w.end) || w.end <= w.start) add(`transcript.words[${i}]: expected text,start,end in source seconds.`);
183037
+ });
183038
+ }
183039
+ const box = (b) => obj2(b) && ["x", "y", "w", "h"].every((k) => number2(b[k]) && b[k] <= 1) && b.w > 0 && b.h > 0 && b.x + b.w <= 1.0001 && b.y + b.h <= 1.0001;
183040
+ if (value.geometry) {
183041
+ const g = value.geometry;
183042
+ if (!obj2(g) || g.timeline !== "final" || g.coords !== "normalized-top-left" || !Array.isArray(g.frames) || !g.frames.length || g.frames.length > 108e3 || !Array.isArray(g.overlays) || !g.overlays.length || g.overlays.length > 1e3) add("geometry requires final timeline, normalized-top-left coordinates, 1\u2013108000 frames and 1\u20131000 overlays.");
183043
+ else {
183044
+ if (g.frames.length * g.overlays.length > 2e6) add("Geometry exceeds the 2 million frame/overlay comparison budget. Split the review into smaller intervals.");
183045
+ g.frames.forEach((f, i) => {
183046
+ if (!obj2(f) || !number2(f.t) || i && f.t <= g.frames[i - 1]?.t || f.face !== null && !box(f.face)) add(`geometry.frames[${i}]: expected increasing t and face rectangle or null.`);
183047
+ });
183048
+ g.overlays.forEach((o, i) => {
183049
+ if (!box(o) || typeof o.id !== "string" || o.id.length > 100 || !number2(o.start) || !number2(o.end) || o.end <= o.start) add(`geometry.overlays[${i}]: expected id,start,end,x,y,w,h.`);
183050
+ });
183051
+ }
183052
+ }
183053
+ if (issues.length) throw new CliError("INVALID_REVIEW_INPUT", "Review evidence has invalid fields.", "Correct all reported fields. Times must be seconds; never reinterpret source coordinates as final coordinates.", false, { issues: issues.slice(0, 100), omittedIssues: Math.max(0, issues.length - 100) });
183054
+ return value;
183055
+ }
183056
+ function evaluateContinuity(input) {
183057
+ let cutFindingCount = 0;
183058
+ const cutFindings = [];
183059
+ for (const [i, p] of (input.cuts?.parts ?? []).entries()) for (const [edge, t, final] of [["start", p.source[0], p.final[0]], ["end", p.source[1], p.final[1]]]) {
183060
+ for (const w of input.transcript.words) if (t > w.start + 0.015 && t < w.end - 0.015) {
183061
+ cutFindingCount++;
183062
+ if (cutFindings.length < 200) cutFindings.push({ part: i, edge, sourceSeconds: t, finalSeconds: final, word: w.text, wordStart: w.start, wordEnd: w.end });
183063
+ }
183064
+ }
183065
+ const occlusions = [];
183066
+ let tested = 0, missingFaces = 0;
183067
+ for (const f of input.geometry?.frames ?? []) {
183068
+ const active = input.geometry.overlays.filter((o) => f.t >= o.start && f.t < o.end);
183069
+ if (!active.length) continue;
183070
+ if (!f.face) {
183071
+ missingFaces++;
183072
+ continue;
183073
+ }
183074
+ for (const o of active) {
183075
+ tested++;
183076
+ const b = f.face;
183077
+ const area = Math.max(0, Math.min(o.x + o.w, b.x + b.w) - Math.max(o.x, b.x)) * Math.max(0, Math.min(o.y + o.h, b.y + b.h) - Math.max(o.y, b.y));
183078
+ if (area > 0) occlusions.push({ id: o.id, t: f.t, faceFraction: area / (b.w * b.h) });
183079
+ }
183080
+ }
183081
+ const uncovered = (input.geometry?.overlays ?? []).filter((o) => !input.geometry.frames.some((f) => f.t >= o.start && f.t < o.end && f.face)).map((o) => o.id);
183082
+ return {
183083
+ cutFindings,
183084
+ cutFindingCount,
183085
+ omittedCutFindings: Math.max(0, cutFindingCount - 200),
183086
+ occlusions: occlusions.slice(0, 200),
183087
+ occlusionCount: occlusions.length,
183088
+ omittedOcclusions: Math.max(0, occlusions.length - 200),
183089
+ testedGeometryPairs: tested,
183090
+ missingFaces,
183091
+ uncoveredOverlays: uncovered,
183092
+ status: cutFindings.length || occlusions.length ? "review_required" : missingFaces || uncovered.length ? "incomplete" : "no_candidates_in_supplied_evidence",
183093
+ coverage: { cuts: input.cuts ? "provided_source_word_intervals" : "not_provided", geometry: input.geometry ? "provided_frames_only" : "not_provided" },
183094
+ limitations: ["Transcript timings and rectangles are supplied evidence, not independently detected or certified.", "No face boxes between sampled frames are inferred. Crops, speed changes and translations must be reflected in the final-coordinate evidence.", "Energy cannot distinguish voice from music or SFX; high energy is a listening-review candidate, never proof of a clipped word."]
183095
+ };
183096
+ }
183097
+ function parseEnergyFrames(text12) {
183098
+ const frames = [];
183099
+ let t;
183100
+ for (const line of text12.split("\n")) {
183101
+ const time = /pts_time:([\d.e+-]+)/.exec(line);
183102
+ if (time) t = Number(time[1]);
183103
+ const rms = /^lavfi\.astats\.Overall\.RMS_level=(-inf|[-\d.]+)$/.exec(line);
183104
+ if (rms && t !== void 0 && Number.isFinite(t)) {
183105
+ frames.push({ t, rmsDb: rms[1] === "-inf" ? null : Number(rms[1]) });
183106
+ t = void 0;
183107
+ }
183108
+ }
183109
+ return frames;
183110
+ }
183111
+ async function checkContinuity(file, artifactSha256, input, duration) {
183112
+ if (duration !== void 0 && duration !== null && ((input.cuts?.parts ?? []).some((p) => p.final[1] > duration + 0.05) || (input.geometry?.frames ?? []).some((f) => f.t > duration + 0.05) || (input.geometry?.overlays ?? []).some((o) => o.end > duration + 0.05))) throw new CliError("REVIEW_TIMELINE_MISMATCH", "Review intervals extend beyond the final render.", "Rebuild the timing map after trims or speed changes.");
183113
+ if (input.artifactSha256 !== artifactSha256) throw new CliError("REVIEW_ARTIFACT_MISMATCH", "Review evidence belongs to another render.", "Regenerate the mapping and geometry for this exact final SHA-256.");
183114
+ const report = evaluateContinuity(input);
183115
+ const boundaries = [...new Set((input.cuts?.parts ?? []).slice(1).map((p) => p.final[0]))];
183116
+ const audio = { status: "not_requested", boundaries: [] };
183117
+ if (boundaries.length) {
183118
+ try {
183119
+ const output2 = await runMediaTool("ffmpeg", ["-hide_banner", "-loglevel", "error", "-nostats", ...localInputArgs(file), "-map", "0:a:0", "-vn", "-af", "aresample=8000,asetnsamples=n=80:p=0,astats=metadata=1:reset=1:measure_perchannel=none:measure_overall=RMS_level,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-", "-f", "null", "-"], { timeoutMs: 12e4, maxOutputBytes: 16 * 1024 * 1024 });
183120
+ const frames = parseEnergyFrames(output2.stdout);
183121
+ audio.status = frames.length ? "measured_first_audio_stream" : "incomplete";
183122
+ audio.boundaries = boundaries.map((t) => {
183123
+ const near = frames.filter((f) => Math.abs(f.t - t) <= 0.02);
183124
+ const finite3 = near.flatMap((f) => f.rmsDb === null ? [] : [f.rmsDb]);
183125
+ const rmsDb = finite3.length ? Math.max(...finite3) : null;
183126
+ return { t, rmsDb, status: !near.length ? "not_measured" : rmsDb !== null && rmsDb > -35 ? "audible_boundary_review" : "low_energy_candidate" };
183127
+ });
183128
+ } catch {
183129
+ audio.status = "incomplete";
183130
+ }
183131
+ }
183132
+ return { ...report, audio, artifactSha256 };
183133
+ }
183134
+ async function loadContinuityInput(root, path) {
183135
+ const value = await readProductionJson(root, path);
183136
+ if (!obj2(value)) return validateContinuityInput(value);
183137
+ const input = { ...value };
183138
+ for (const key of ["cuts", "transcript"]) if (obj2(input[key]) && input[key].file !== void 0) {
183139
+ const spec = input[key];
183140
+ if (typeof spec.file !== "string" || Object.keys(spec).some((k) => !["file", "sourceSha256"].includes(k))) throw new CliError("INVALID_REVIEW_INPUT", `${key}: use file and sourceSha256 only.`, "Do not mix inline and file-backed evidence.");
183141
+ const doc = await readProductionJson(root, spec.file);
183142
+ if (!obj2(doc)) throw new Error(`${key}: expected JSON object`);
183143
+ if (doc.sourceSha256 && doc.sourceSha256 !== spec.sourceSha256) throw new CliError("REVIEW_SOURCE_MISMATCH", `${key}: source hash differs.`, "Use transcription and cutmap from the same source media.");
183144
+ input[key] = key === "cuts" ? { sourceSha256: spec.sourceSha256, parts: doc.parts } : { sourceSha256: spec.sourceSha256, words: doc.words };
183145
+ }
183146
+ if (obj2(input.geometry) && input.geometry.trackFile !== void 0) {
183147
+ const spec = input.geometry;
183148
+ if (typeof spec.trackFile !== "string" || typeof spec.overlaysFile !== "string" || Object.keys(spec).some((k) => !["trackFile", "overlaysFile", "timeline", "coords"].includes(k))) throw new CliError("INVALID_REVIEW_INPUT", "geometry: use trackFile, overlaysFile, timeline and coords.", "Do not mix inline and file-backed geometry.");
183149
+ const track = await readProductionJson(root, spec.trackFile), overlays = await readProductionJson(root, spec.overlaysFile);
183150
+ if (!obj2(track) || !Array.isArray(track.per_frame) || !obj2(overlays) || !Array.isArray(overlays.overlays)) throw new CliError("INVALID_REVIEW_INPUT", "Expected track.per_frame and overlays.overlays arrays.", "Only tracks already transformed to final frame coordinates are supported.");
183151
+ input.geometry = { timeline: spec.timeline, coords: spec.coords, frames: track.per_frame.map((f) => ({ t: f?.t, face: f?.face && (f.face.conf === void 0 || f.face.conf >= 0.7) ? { x: f.face.x, y: f.face.y, w: f.face.w, h: f.face.h } : null })), overlays: overlays.overlays };
183152
+ }
183153
+ return validateContinuityInput(input);
183154
+ }
183155
+
183156
+ // packages/cli/src/project-variants.ts
183157
+ import { mkdir as mkdir3, readdir as readdir2 } from "node:fs/promises";
183158
+ import { createHash as createHash2 } from "node:crypto";
183159
+
183160
+ // packages/cli/src/workspace-lock.ts
183161
+ import { constants as constants4 } from "node:fs";
183162
+ import { lstat as lstat3, open as open4, rename as rename2, unlink as unlink2 } from "node:fs/promises";
183163
+ import { hostname } from "node:os";
183164
+ import { randomUUID as randomUUID2 } from "node:crypto";
183165
+ var LOCK_PATH = ".editorbrain-operation.lock";
183166
+ async function withWorkspaceLock(root, operation, options = {}) {
183167
+ const legacyLock = await checkedPath(root, ".editorharness-operation.lock", false);
183168
+ let legacy;
183169
+ try {
183170
+ legacy = await open4(legacyLock, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY | constants4.O_NOFOLLOW, 384);
183171
+ } catch (error) {
183172
+ if (error.code === "EEXIST") throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation to finish.");
183173
+ throw error;
183174
+ }
183175
+ try {
183176
+ const path = await checkedPath(root, LOCK_PATH, false);
183177
+ let handle;
183178
+ try {
183179
+ handle = await open4(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY | constants4.O_NOFOLLOW, 384);
183180
+ } catch (error) {
183181
+ if (error.code !== "EEXIST") throw error;
183182
+ throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation. If it crashed, verify no process is using the folder before removing .editorbrain-operation.lock. Locks are never removed automatically.");
183183
+ }
183184
+ const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID2(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
183185
+ try {
183186
+ await handle.writeFile(owner);
183187
+ await handle.close();
183188
+ const oldRoot = await checkedPath(root, ".editorharness", false);
183189
+ const newRoot = await checkedPath(root, ".editorbrain", false);
183190
+ const exists3 = async (path2) => lstat3(path2).then(() => true, (error) => {
183191
+ if (error.code === "ENOENT") return false;
183192
+ throw error;
183193
+ });
183194
+ if (options.migrateLegacy !== false && await exists3(oldRoot)) {
183195
+ if (await exists3(newRoot)) throw new CliError("WORKSPACE_PATH_CONFLICT", "This folder contains two versions of the workspace directory.", "Reconcile the directories before continuing; neither was changed.");
183196
+ await rename2(oldRoot, newRoot);
183197
+ }
183198
+ return await operation();
183199
+ } finally {
183200
+ await handle.close().catch(() => {
183201
+ });
183202
+ if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
183203
+ }
183204
+ } finally {
183205
+ await legacy.close();
183206
+ await unlink2(legacyLock);
183207
+ }
183208
+ }
183209
+
183210
+ // packages/cli/src/project-variants.ts
183211
+ async function projectVariants(directory, project, operation, id3, changes) {
183212
+ const root = await ensureRoot(directory);
183213
+ assertIdentifier(project);
183214
+ const projectRaw = await readText(root, `videos/${project}/project.json`);
183215
+ if (!validateDocument(`videos/${project}/project.json`, projectRaw).valid) throw new CliError("INVALID_PROJECT", "Base project is invalid.", "Run validate before creating variants.");
183216
+ const base = `.editorbrain-local/${project}/variants`;
183217
+ if (operation === "list") {
183218
+ let entries;
183219
+ try {
183220
+ entries = await readdir2(await checkedPath(root, base, false), { withFileTypes: true });
183221
+ } catch (e) {
183222
+ if (e.code === "ENOENT") return { variants: [] };
183223
+ throw e;
183224
+ }
183225
+ const variants = [], issues = [];
183226
+ if (entries.length > 1e3) throw new Error("Variant inventory exceeds 1000 entries.");
183227
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
183228
+ if (e.name.startsWith(".")) continue;
183229
+ assertIdentifier(e.name);
183230
+ if (!e.isDirectory() || e.isSymbolicLink()) {
183231
+ issues.push({ id: e.name, message: "Expected a real variant directory." });
183232
+ continue;
183233
+ }
183234
+ let raw;
183235
+ try {
183236
+ raw = await readText(root, `${base}/${e.name}/variant.json`, false);
183237
+ } catch (error) {
183238
+ if (error.code === "ENOENT") {
183239
+ issues.push({ id: e.name, message: "Incomplete variant: no committed manifest. Preserve its files and inspect before reusing this ID." });
183240
+ continue;
183241
+ }
183242
+ throw error;
183243
+ }
183244
+ const item = JSON.parse(raw);
183245
+ let baseChanged = false;
183246
+ for (const [path, sha] of Object.entries(item.sourceHashes ?? {})) {
183247
+ const text12 = await readText(root, path).catch(() => null);
183248
+ if (text12 === null || createHash2("sha256").update(text12).digest("hex") !== sha) baseChanged = true;
183249
+ }
183250
+ variants.push({ ...item, baseChanged });
183251
+ }
183252
+ return { project, variants, issues };
183253
+ }
183254
+ if (operation !== "create" || !id3) throw new CliError("INVALID_ARGUMENT", "Use variants create ID --project BASE --file changes.json or variants list --project BASE.", "Variants are local edit specifications; no media or approvals are copied.");
183255
+ assertIdentifier(id3);
183256
+ const c = changes;
183257
+ if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).some((k) => !["hook", "cta", "instructions"].includes(k)) || !Object.keys(c).length || Object.values(c).some((v) => typeof v !== "string" || !v.trim() || v.length > 4e3)) throw new CliError("INVALID_VARIANT", "Use hook, cta and/or instructions as nonempty text (up to 4000 characters each).", "Only scoped changes belong here; the base brand and editing preferences remain unchanged.");
183258
+ return withWorkspaceLock(root, async () => {
183259
+ const sourceHashes = {}, documents = {};
183260
+ for (const [path, text12] of Object.entries(await readProjectWorkspace(root, project))) sourceHashes[path] = createHash2("sha256").update(text12).digest("hex");
183261
+ for (const name of ["project.json", "brief.md", "direction.md"]) {
183262
+ const path = `videos/${project}/${name}`;
183263
+ let text12;
183264
+ try {
183265
+ text12 = await readText(root, path);
183266
+ } catch (e) {
183267
+ if (e.code === "ENOENT" && name !== "project.json") continue;
183268
+ throw e;
183269
+ }
183270
+ documents[name] = text12;
183271
+ sourceHashes[path] = createHash2("sha256").update(text12).digest("hex");
183272
+ }
183273
+ const target = `${base}/${id3}`;
183274
+ await mkdir3(await checkedPath(root, base, false), { recursive: true });
183275
+ try {
183276
+ await mkdir3(await checkedPath(root, target, false));
183277
+ } catch (e) {
183278
+ if (e.code === "EEXIST") throw new CliError("VARIANT_EXISTS", `Variant ${id3} exists.`, "Choose a new variant ID.");
183279
+ throw e;
183280
+ }
183281
+ const manifest = { schemaVersion: 1, kind: "editorbrain.edit-variant", id: id3, project, brand: JSON.parse(projectRaw).brand, sourceHashes, changes: c, mediaRoot: `.editorbrain-local/${project}`, outputDirectory: `${target}/renders`, status: "draft", requiresTimingReview: true, approvalInherited: false };
183282
+ try {
183283
+ for (const [name, text12] of Object.entries(documents)) await atomicWrite(root, `${target}/${name}`, text12, { document: false, overwrite: false });
183284
+ await atomicWrite(root, `${target}/variant.json`, stableJson(manifest), { document: false, overwrite: false });
183285
+ } catch (error) {
183286
+ throw new CliError("VARIANT_WRITE_INCOMPLETE", `Variant ${id3} could not be completed. Files already written remain at ${target}.`, "Inspect the partial directory and the base project. Choose a new variant ID after resolving the filesystem error.", false, { causeCode: error.code ?? "WRITE_FAILED" });
183287
+ }
183288
+ return { ...manifest, path: `${target}/variant.json`, next: "Read this specification with the base project context. Reuse source media by path, adapt cutmap/cues for the changed hook or CTA, then render to outputDirectory and verify that exact file. This does not render or certify a new edit; do not reuse base approval." };
183289
+ }, { migrateLegacy: false });
183290
+ }
183291
+
183292
+ // packages/cli/src/project-disk.ts
183293
+ import { constants as constants5 } from "node:fs";
183294
+ import { open as open5, readdir as readdir3, lstat as lstat4, copyFile, rename as rename3, unlink as unlink3, chmod, utimes } from "node:fs/promises";
183295
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
183296
+ import { dirname as dirname4, join as join2 } from "node:path";
183297
+ async function fingerprintFile(path) {
183298
+ const h = await open5(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
183299
+ try {
183300
+ const before = await h.stat();
183301
+ if (!before.isFile()) throw new Error("Expected a regular file.");
183302
+ const hash9 = createHash3("sha256");
183303
+ const buffer = Buffer.alloc(1024 * 1024);
183304
+ let offset = 0;
183305
+ while (offset < before.size) {
183306
+ const { bytesRead } = await h.read(buffer, 0, Math.min(buffer.length, before.size - offset), offset);
183307
+ if (!bytesRead) throw new Error("File changed while hashing.");
183308
+ hash9.update(buffer.subarray(0, bytesRead));
183309
+ offset += bytesRead;
183310
+ }
183311
+ const after = await h.stat();
183312
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new Error("File changed while hashing.");
183313
+ return { sha256: hash9.digest("hex"), bytes: before.size, ino: before.ino, dev: before.dev, mtimeMs: before.mtimeMs, atimeMs: before.atimeMs, mode: before.mode };
183314
+ } finally {
183315
+ await h.close();
183316
+ }
183317
+ }
183318
+ async function projectDisk(root, project) {
183319
+ assertIdentifier(project);
183320
+ await readText(root, `videos/${project}/project.json`);
183321
+ const prefix = `.editorbrain-local/${project}`, files = [], skipped = [];
183322
+ let bytes = 0, count = 0;
183323
+ async function walk(dir, depth) {
183324
+ if (depth > 16) throw new CliError("DISK_SCAN_LIMIT", "Project exceeds 16 directory levels.", "Inspect the project manually; nothing was removed.");
183325
+ let entries;
183326
+ try {
183327
+ entries = await readdir3(await checkedPath(root, dir, false), { withFileTypes: true });
183328
+ } catch (e) {
183329
+ if (e.code === "ENOENT") return;
183330
+ throw e;
183331
+ }
183332
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
183333
+ if (++count > 2e4) throw new CliError("DISK_SCAN_LIMIT", "Project exceeds 20000 entries.", "Nothing was removed.");
183334
+ const path = `${dir}/${e.name}`;
183335
+ if (e.isSymbolicLink() || !e.isDirectory() && !e.isFile()) {
183336
+ skipped.push(path);
183337
+ continue;
183338
+ }
183339
+ if (e.isDirectory()) await walk(path, depth + 1);
183340
+ else {
183341
+ const target = await checkedPath(root, path, false), st = await lstat4(target);
183342
+ bytes += st.size;
183343
+ if (bytes > 30 * 1024 ** 3) throw new CliError("DISK_SCAN_LIMIT", "Project exceeds the 30 GiB inspection budget.", "Inspect a smaller project; nothing was removed.");
183344
+ const f = await fingerprintFile(target);
183345
+ files.push({ path, bytes: f.bytes, sha256: f.sha256 });
183346
+ }
183347
+ }
183348
+ }
183349
+ await walk(prefix, 0);
183350
+ const grouped = /* @__PURE__ */ new Map();
183351
+ for (const f of files) {
183352
+ const group = grouped.get(f.sha256) ?? [];
183353
+ group.push(f);
183354
+ grouped.set(f.sha256, group);
183355
+ }
183356
+ const duplicates = [...grouped.values()].filter((g) => g.length > 1 && g[0].bytes > 0).map((g) => ({ sha256: g[0].sha256, bytes: g[0].bytes, paths: g.map((f) => f.path), logicalDuplicateBytes: g[0].bytes * (g.length - 1) }));
183357
+ return { schemaVersion: 1, kind: "editorbrain.project-disk", project, totalBytes: bytes, files, duplicates, skipped, logicalDuplicateBytes: duplicates.reduce((n, g) => n + g.logicalDuplicateBytes, 0), physicalSavingsVerified: false, deleted: [], next: "Review duplicates. clean --project ID --deduplicate --confirm shares copy-on-write blocks on supported filesystems without hardlinks or deleting paths. Existing sources, masters and receipts remain independent." };
183358
+ }
183359
+ async function cleanProject(directory, project, options = {}) {
183360
+ const root = await ensureRoot(directory);
183361
+ if (options.confirm && !options.deduplicate || options.deduplicate && !options.confirm) throw new CliError("CLEAN_CONFIRMATION_REQUIRED", "Deduplication requires --deduplicate --confirm together.", "First run clean --project ID to inspect. This never deletes project files.");
183362
+ const run = async () => {
183363
+ const audit = await projectDisk(root, project), cloned = [], warnings = [];
183364
+ if (options.deduplicate) for (const group of audit.duplicates) {
183365
+ const source2 = await checkedPath(root, group.paths[0], false);
183366
+ for (const path of group.paths.slice(1)) {
183367
+ const target = await checkedPath(root, path, false), before = await fingerprintFile(target), src = await fingerprintFile(source2);
183368
+ if (before.sha256 !== group.sha256 || src.sha256 !== group.sha256) throw new CliError("DISK_FILE_CHANGED", "A duplicate changed after inspection.", "Rerun inspection; changed files were not replaced.");
183369
+ const temp = join2(dirname4(target), `.eb-clone-${randomUUID3()}`);
183370
+ try {
183371
+ await copyFile(source2, temp, constants5.COPYFILE_EXCL | constants5.COPYFILE_FICLONE_FORCE);
183372
+ await chmod(temp, before.mode & 511);
183373
+ await utimes(temp, before.atimeMs / 1e3, before.mtimeMs / 1e3);
183374
+ if ((await fingerprintFile(temp)).sha256 !== group.sha256) throw new Error("Cloned file hash mismatch.");
183375
+ const current2 = await fingerprintFile(await checkedPath(root, path, false));
183376
+ if (current2.ino !== before.ino || current2.dev !== before.dev || current2.mtimeMs !== before.mtimeMs || current2.sha256 !== before.sha256) throw new CliError("DISK_FILE_CHANGED", `File changed: ${path}`, "Stop rendering before deduplicating.");
183377
+ await rename3(temp, target);
183378
+ cloned.push(path);
183379
+ } catch (e) {
183380
+ if (["ENOTSUP", "ENOSYS", "EXDEV", "EINVAL", "EOPNOTSUPP"].includes(e.code ?? "")) {
183381
+ warnings.push("Filesystem does not support copy-on-write clones. No fallback copies or hardlinks were created.");
183382
+ return { ...audit, cloned, warnings };
183383
+ }
183384
+ throw e;
183385
+ } finally {
183386
+ await unlink3(temp).catch((e) => {
183387
+ if (e.code !== "ENOENT") throw e;
183388
+ });
183389
+ }
183390
+ }
183391
+ }
183392
+ return { ...audit, cloned, warnings };
183393
+ };
183394
+ return options.deduplicate ? withWorkspaceLock(root, run, { migrateLegacy: false }) : run();
183395
+ }
183396
+
183397
+ // packages/cli/src/command-help.ts
183398
+ var introductions = {
183399
+ styles: "Estilos de edici\xF3n completos. list = biblioteca publicada; mine = estilos locales de este workspace. media styles son recetas visuales para generar im\xE1genes, no ediciones completas.",
183400
+ production: "Revisi\xF3n local del resultado. Un chequeo t\xE9cnico no aprueba la calidad creativa. verify mide el archivo final; los chequeos de cortes/caras requieren evidencia alineada al mismo render.",
183401
+ studio: "Herramientas de generaci\xF3n: catalog \u2192 quote \u2192 run \u2192 get. Una cotizaci\xF3n no gasta; run requiere presupuesto autorizado. Las capacidades dependen del proveedor y del plan.",
183402
+ clean: "Primero inspecciona el disco. No elimina fuentes, masters ni recibos autom\xE1ticamente. --deduplicate usa copias independientes con bloques compartidos cuando el sistema lo admite.",
183403
+ variants: "Variantes locales: reutilizan la edici\xF3n base y registran cambios de gancho/CTA sin duplicar medios ni modificar el proyecto original."
183404
+ };
183405
+ function commandHelp(help, path) {
183406
+ if (!path.length) return help;
183407
+ const prefix = `editorbrain ${path.join(" ")}`;
183408
+ const lines = help.split("\n").filter((line) => line === prefix || line.startsWith(prefix + " ") || line.startsWith(prefix + "|"));
183409
+ if (!lines.length) throw new CliError("UNKNOWN_COMMAND", `No existe ayuda para ${path.join(" ")}.`, "Usa editorbrain --help para ver los grupos disponibles.");
183410
+ return `${prefix}
183411
+
183412
+ ${introductions[path[0]] ?? "Opciones espec\xEDficas de este comando."}
183413
+
183414
+ ${lines.join("\n")}
183415
+
183416
+ Usa --help despu\xE9s de un subcomando para ver su sintaxis.
183417
+ `;
183418
+ }
183419
+
183420
+ // packages/cli/src/local-styles.ts
183421
+ import { readdir as readdir4 } from "node:fs/promises";
183422
+ async function listLocalStyles(directory) {
183423
+ const root = await ensureRoot(directory), styles = [], issues = [];
183424
+ for (const prefix of [".editorbrain", ".editorharness"]) {
183425
+ const base = `${prefix}/styles`;
183426
+ let entries;
183427
+ try {
183428
+ entries = await readdir4(await checkedPath(root, base, false), { withFileTypes: true });
183429
+ } catch (e) {
183430
+ if (e.code === "ENOENT") continue;
183431
+ throw e;
183432
+ }
183433
+ if (entries.length > 1e3) throw new Error("Local style inventory exceeds 1000 entries.");
183434
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
183435
+ const path = `${base}/${entry.name}/style.json`;
183436
+ try {
183437
+ assertIdentifier(entry.name);
183438
+ if (!entry.isDirectory() || entry.isSymbolicLink()) throw new Error("Expected a real style directory.");
183439
+ const doc = JSON.parse(await readText(root, path));
183440
+ styles.push({ id: entry.name, name: typeof doc.name === "string" ? doc.name : entry.name, path });
183441
+ } catch (e) {
183442
+ issues.push({ path, message: e.message });
183443
+ }
183444
+ }
183445
+ }
183446
+ return { scope: "local_workspace", styles, issues, next: "Use styles check <id> to validate a local style; styles list discovers the published library. Pull a cloud style explicitly with styles pull <id>." };
183447
+ }
183448
+
183449
+ // packages/cli/src/style-assets.ts
183450
+ import { posix } from "node:path";
183451
+ function styleAssetPath(id3, source2) {
183452
+ assertIdentifier(id3);
183453
+ if (!/^[a-f0-9]{64}$/.test(source2.assetId)) throw new Error("Invalid asset hash");
183454
+ const ext = source2.fileName ? posix.extname(source2.fileName).toLowerCase() : ".bin";
183455
+ if (!/^\.[a-z0-9]{1,10}$/.test(ext)) throw new Error("Invalid asset extension");
183456
+ return `production-assets/styles/${id3}/${source2.assetId}${ext}`;
183457
+ }
183458
+
183459
+ // packages/cli/src/style-sync.ts
183460
+ import { createHash as createHash6 } from "node:crypto";
183461
+ import { lstat as lstat7 } from "node:fs/promises";
183462
+ import { posix as posix3 } from "node:path";
183463
+
182685
183464
  // packages/cli/src/client.ts
183465
+ import { setTimeout as delay } from "node:timers/promises";
182686
183466
  var searchErrors = {
182687
183467
  email_verification_required: { status: 403, code: "EMAIL_VERIFICATION_REQUIRED", hint: "Verifica tu correo en https://editorbrain.com/app/settings y vuelve a intentar. Cambiar de plan o comprar cr\xE9ditos no resuelve la verificaci\xF3n." },
182688
183468
  resource_policy_unavailable: { status: 503, code: "RESOURCE_POLICY_UNAVAILABLE", hint: "La pol\xEDtica de recursos no est\xE1 disponible. Contin\xFAa el trabajo independiente y consulta el estado del servicio; recargar cr\xE9ditos no lo resuelve." },
@@ -182708,6 +183488,10 @@ var searchErrors = {
182708
183488
  studio_preference_conflict: { status: 409, code: "STUDIO_PREFERENCE_CONFLICT", hint: "Reconcile project language, voice, music or media-source preferences before generating." },
182709
183489
  studio_audio_format: { status: 422, code: "STUDIO_AUDIO_FORMAT", hint: "Prepare PCM 16-bit WAV from the original with studio prepare, then upload it." },
182710
183490
  studio_invalid_input: { status: 400, code: "STUDIO_INVALID_INPUT", hint: "Check studio catalog and the request fields; never send provider credentials." },
183491
+ studio_references_require_premium: { status: 422, code: "STUDIO_REFERENCES_REQUIRE_PREMIUM", hint: "Reference images require Prism Premium. Review saved preferences and explicitly choose Premium before requesting a new quote; never increase the budget automatically." },
183492
+ studio_reference_invalid: { status: 400, code: "STUDIO_REFERENCE_INVALID", hint: "Use up to four unique SHA-256 asset IDs uploaded to this workspace, not URLs or file paths." },
183493
+ studio_reference_format: { status: 422, code: "STUDIO_REFERENCE_FORMAT", hint: "Use PNG, JPEG or WebP, up to 8 MiB each and 20 MiB total. Convert SVG to PNG locally before upload." },
183494
+ studio_reference_missing: { status: 404, code: "STUDIO_REFERENCE_MISSING", hint: "A reference is unavailable in the selected workspace. Verify assets list or upload the intended file; never switch accounts automatically." },
182711
183495
  studio_queue_full: { status: 429, code: "STUDIO_QUEUE_FULL", hint: "Wait for existing Studio jobs to finish. Do not create replacement quotes." },
182712
183496
  billing_review_required: { status: 409, code: "BILLING_REVIEW_REQUIRED", hint: "A payment needs review. Contact support before starting another paid job." },
182713
183497
  batch_changed: { status: 409, code: "BATCH_CHANGED", hint: "Read batches get before retrying; preserve new changes." },
@@ -182741,6 +183525,14 @@ function safeDiagnosticDetails(body) {
182741
183525
  for (const key of ["limit", "retryAfter"]) if (Number.isSafeInteger(e[key]) && Number(e[key]) >= 0 && Number(e[key]) <= 86400) details[key] = Number(e[key]);
182742
183526
  if (["workspace", "service"].includes(String(e.scope))) details.scope = String(e.scope);
182743
183527
  if (["service_paused", "tool_paused", "configuration_pending", "pricing_pending"].includes(String(e.availabilityCode))) details.availabilityCode = String(e.availabilityCode);
183528
+ if (e.code === "studio_invalid_input") {
183529
+ const allowed = /* @__PURE__ */ new Set(["tool", "projectId", "preferenceOverrideReason", "assetId", "language", "prompt", "referenceAssetIds", "quality", "resolution", "aspectRatio", "durationSeconds", "character", "text", "voice", "quoteId", "maxCredits", "userConfirmed", "batchLeaseToken", "request"]);
183530
+ if (typeof e.invalidFields === "string" && e.invalidFields.length <= 512) {
183531
+ const fields = e.invalidFields.split(",").filter((f) => allowed.has(f));
183532
+ if (fields.length) details.invalidFields = [...new Set(fields)].join(",");
183533
+ }
183534
+ if (Number.isSafeInteger(e.issueCount) && Number(e.issueCount) > 0 && Number(e.issueCount) <= 1e3) details.issueCount = Number(e.issueCount);
183535
+ }
182744
183536
  return details;
182745
183537
  }
182746
183538
  var ApiError = class extends CliError {
@@ -182869,12 +183661,12 @@ var Client = class {
182869
183661
  return this.request(`/v1/documents/${safeDocumentPath(path).split("/").map(encodeURIComponent).join("/")}`, { method: "PUT", body: { content, expectedRevision } });
182870
183662
  }
182871
183663
  async uploadPreview(path, content, mimeType) {
182872
- const hash8 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
182873
- if (!hash8 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
183664
+ const hash9 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
183665
+ if (!hash9 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
182874
183666
  const sourceHash = new URL(path, this.url).searchParams.get("sourceSha256");
182875
- if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash8)) throw new Error("Use a distinct original SHA-256, or omit it.");
183667
+ if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash9)) throw new Error("Use a distinct original SHA-256, or omit it.");
182876
183668
  let plan;
182877
- const params = new URLSearchParams({ sha256: hash8, bytes: String(content.byteLength) });
183669
+ const params = new URLSearchParams({ sha256: hash9, bytes: String(content.byteLength) });
182878
183670
  const projectId = new URL(path, "https://local.invalid").searchParams.get("projectId");
182879
183671
  if (projectId) params.set("projectId", projectId);
182880
183672
  try {
@@ -182886,7 +183678,7 @@ var Client = class {
182886
183678
  if (typeof plan.allowed !== "boolean" || !Number.isSafeInteger(plan.additionalBytes)) throw new Error("Invalid preview preflight response.");
182887
183679
  if (plan.existingAsset) {
182888
183680
  const asset = plan.existingAsset;
182889
- if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash8 || asset.sha256 !== hash8 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
183681
+ if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash9 || asset.sha256 !== hash9 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
182890
183682
  return new Response(JSON.stringify({ ...asset, reused: true }), { headers: { "Content-Type": "application/json" } });
182891
183683
  }
182892
183684
  if (!plan.allowed) throw new CliError("PREVIEW_STORAGE_FULL", "There is not enough cloud storage for this review copy. Your local edit is intact.", "Continue on the computer, prepare a smaller legible preview, or review eligible files at https://editorbrain.com/app/files. Do not delete protected media or upgrade a plan automatically.");
@@ -183043,17 +183835,17 @@ ${conflicts.join("\n")}`, "Run pull --dry-run and reconcile the reported paths."
183043
183835
  }
183044
183836
 
183045
183837
  // packages/cli/src/style-project.ts
183046
- import { createHash } from "node:crypto";
183047
- import { constants as constants3 } from "node:fs";
183048
- import { readdir as readdir2, lstat as lstat2, open as open3 } from "node:fs/promises";
183838
+ import { createHash as createHash4 } from "node:crypto";
183839
+ import { constants as constants7 } from "node:fs";
183840
+ import { readdir as readdir5, lstat as lstat5, open as open7 } from "node:fs/promises";
183049
183841
  import { posix as posix2 } from "node:path";
183050
183842
 
183051
183843
  // packages/cli/src/review-files.ts
183052
- import { constants as constants2 } from "node:fs";
183053
- import { open as open2 } from "node:fs/promises";
183844
+ import { constants as constants6 } from "node:fs";
183845
+ import { open as open6 } from "node:fs/promises";
183054
183846
  var REVIEW_MEDIA_BYTES = 24 * 1024 * 1024;
183055
183847
  async function readReviewFile(path, maxBytes) {
183056
- const handle = await open2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
183848
+ const handle = await open6(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
183057
183849
  try {
183058
183850
  const before = await handle.stat();
183059
183851
  if (!before.isFile() || before.size <= 0 || before.size > maxBytes) throw new CliError("INVALID_REVIEW_FILE", "Review file is empty, not regular or exceeds the preview size limit.", "Use a lightweight review copy under 24 MiB per medium. Keep the master unchanged.");
@@ -183073,35 +183865,35 @@ async function readReviewFile(path, maxBytes) {
183073
183865
  }
183074
183866
 
183075
183867
  // packages/cli/src/style-project.ts
183076
- var media = /\.(png|jpe?g|webp|mp4|mov|webm|wav|mp3|m4a|ogg|woff2?|ttf|otf|html|js|mjs)$/i;
183077
- var digest2 = (b) => createHash("sha256").update(b).digest("hex");
183868
+ var media = /\.(svg|png|jpe?g|webp|mp4|mov|webm|wav|mp3|m4a|ogg|woff2?|ttf|otf|html|js|mjs)$/i;
183869
+ var digest2 = (b) => createHash4("sha256").update(b).digest("hex");
183078
183870
  var object7 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
183079
183871
  function generationReceipt(value) {
183080
183872
  if (!object7(value)) return;
183081
183873
  for (const v of [value, value.data, value.result]) if (object7(v) && (typeof v.model === "string" || typeof v.provider === "string") && ["prompt", "input", "output", "outputs", "outputPath", "path", "result", "taskId", "jobId", "tasks", "jobs"].some((k) => v[k] !== void 0)) return v;
183082
183874
  }
183083
- var kind = (path) => /\.(png|jpe?g|webp)$/i.test(path) ? "image" : /\.(mp4|mov|webm)$/i.test(path) ? "video" : /\.(mp3|wav|m4a|ogg)$/i.test(path) ? "audio" : /\.(woff2?|ttf|otf)$/i.test(path) ? "font" : "script";
183875
+ var kind = (path) => /\.(svg|png|jpe?g|webp)$/i.test(path) ? "image" : /\.(mp4|mov|webm)$/i.test(path) ? "video" : /\.(mp3|wav|m4a|ogg)$/i.test(path) ? "audio" : /\.(woff2?|ttf|otf)$/i.test(path) ? "font" : "script";
183084
183876
  async function videoEvidenceHash(path, expectedSize) {
183085
- const handle = await open3(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
183877
+ const handle = await open7(path, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
183086
183878
  try {
183087
183879
  const before = await handle.stat();
183088
183880
  if (!before.isFile() || before.size !== expectedSize) throw new Error("Video changed before hashing");
183089
- const hash8 = createHash("sha256"), chunk = Buffer.alloc(1024 * 1024);
183881
+ const hash9 = createHash4("sha256"), chunk = Buffer.alloc(1024 * 1024);
183090
183882
  let offset = 0;
183091
183883
  while (offset < before.size) {
183092
183884
  const { bytesRead } = await handle.read(chunk, 0, Math.min(chunk.length, before.size - offset), offset);
183093
183885
  if (!bytesRead) throw new Error("Video changed while hashing");
183094
- hash8.update(chunk.subarray(0, bytesRead));
183886
+ hash9.update(chunk.subarray(0, bytesRead));
183095
183887
  offset += bytesRead;
183096
183888
  }
183097
183889
  const after = await handle.stat();
183098
183890
  if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new Error("Video changed while hashing");
183099
- return hash8.digest("hex");
183891
+ return hash9.digest("hex");
183100
183892
  } finally {
183101
183893
  await handle.close();
183102
183894
  }
183103
183895
  }
183104
- async function buildStyleFromProject(root, id3, projectId, name) {
183896
+ async function buildStyleFromProject(root, id3, projectId, name, scenePath) {
183105
183897
  assertIdentifier(projectId);
183106
183898
  const prefix = `videos/${projectId}`, projectPath = `${prefix}/project.json`;
183107
183899
  const raw = await readText(root, projectPath);
@@ -183118,9 +183910,9 @@ async function buildStyleFromProject(root, id3, projectId, name) {
183118
183910
  warnings.push(`Directory depth limit: ${directory}`);
183119
183911
  return;
183120
183912
  }
183121
- for (const entry of (await readdir2(await checkedPath(root, directory, false), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
183913
+ for (const entry of (await readdir5(await checkedPath(root, directory, false), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
183122
183914
  if (++scanned > 2e3) throw new Error("Project capture exceeds 2000 entries; select a smaller project or an explicit resource manifest.");
183123
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
183915
+ if (entry.name.startsWith(".") || ["node_modules", "vendor", "qa", "frames", "source", "scene-sources", "render-report-history"].includes(entry.name)) continue;
183124
183916
  const path = `${directory}/${entry.name}`;
183125
183917
  try {
183126
183918
  safeStyleResourcePath(path);
@@ -183153,7 +183945,7 @@ async function buildStyleFromProject(root, id3, projectId, name) {
183153
183945
  }
183154
183946
  for (const directory of roots) {
183155
183947
  try {
183156
- const info = await lstat2(await checkedPath(root, directory, false));
183948
+ const info = await lstat5(await checkedPath(root, directory, false));
183157
183949
  if (!info.isDirectory()) throw new Error(`Project capture root is not a directory: ${directory}`);
183158
183950
  } catch (error) {
183159
183951
  if (error.code === "ENOENT") continue;
@@ -183177,7 +183969,7 @@ async function buildStyleFromProject(root, id3, projectId, name) {
183177
183969
  for (const candidate of paths2) try {
183178
183970
  safeStyleResourcePath(candidate);
183179
183971
  if (!allowed(candidate)) continue;
183180
- const info = await lstat2(await checkedPath(root, candidate, false));
183972
+ const info = await lstat5(await checkedPath(root, candidate, false));
183181
183973
  if (info.isFile()) existing.add(candidate);
183182
183974
  } catch {
183183
183975
  }
@@ -183187,62 +183979,104 @@ async function buildStyleFromProject(root, id3, projectId, name) {
183187
183979
  }
183188
183980
  }
183189
183981
  for (const entry of jsonFiles) await discover(entry.value, entry.path);
183190
- for (const path of [...candidates].filter((p) => p.endsWith(".html"))) {
183191
- try {
183192
- const html = (await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024)).toString();
183193
- for (const m of html.matchAll(/(?:src\s*=\s*["']|url\(["']?)([^"')\s>]+)/g)) {
183194
- const child = posix2.join(posix2.dirname(path), m[1]);
183195
- try {
183196
- safeStyleResourcePath(child);
183197
- if (media.test(child) && allowed(child)) candidates.add(child);
183198
- } catch {
183199
- }
183982
+ const sceneCandidates = [...candidates].filter((p) => p.endsWith("/scene.html"));
183983
+ const reviewed = sceneCandidates.filter((p) => (notes.get("review.md") ?? []).includes(posix2.join(posix2.dirname(p), "review.md")));
183984
+ let scenes = scenePath ? [scenePath] : reviewed.length ? reviewed : sceneCandidates;
183985
+ if (scenePath) {
183986
+ safeStyleResourcePath(scenePath);
183987
+ if (!allowed(scenePath) || !scenePath.endsWith(".html")) throw new Error("--scene must be an HTML file inside this project or production-assets.");
183988
+ await checkedPath(root, scenePath, false);
183989
+ }
183990
+ if (scenes.length > 1) throw new Error(`Multiple production scenes: ${scenes.join(", ")}. Choose one with --scene <workspace-relative scene.html>; discarded revisions must not be combined.`);
183991
+ const sceneDirs = scenes.map((p) => posix2.dirname(p)), used = new Set(scenes);
183992
+ const lowValue = (p) => /(?:^|\/)(?:vendor|qa|frames|scene-sources|source|montage|clip|clip-comenta|style-footage)(?:\/|$)/i.test(p);
183993
+ async function locate(locator, parent) {
183994
+ if (/^(?:[a-z]+:|\/)|[\\\x00]/i.test(locator)) return;
183995
+ const paths2 = /* @__PURE__ */ new Set();
183996
+ if (/^(?:videos|\.editorbrain-local|production-assets)\//.test(locator)) paths2.add(locator);
183997
+ else {
183998
+ paths2.add(posix2.join(posix2.dirname(parent), locator));
183999
+ paths2.add(posix2.join(posix2.dirname(parent), "media", locator));
184000
+ for (const r of roots) {
184001
+ paths2.add(posix2.join(r, locator));
184002
+ paths2.add(posix2.join(r, "build", locator));
183200
184003
  }
184004
+ }
184005
+ const found = [];
184006
+ for (const path of paths2) try {
184007
+ safeStyleResourcePath(path);
184008
+ if (allowed(path) && (await lstat5(await checkedPath(root, path, false))).isFile()) found.push(path);
183201
184009
  } catch {
183202
- warnings.push(`Could not inspect scene dependencies: ${path}`);
183203
184010
  }
184011
+ return found.length === 1 ? found[0] : void 0;
183204
184012
  }
183205
- if (candidates.size > 500) throw new Error("More than 500 candidate resources; curate this project before capturing it.");
183206
- const resources = [], examples = [], hashes = /* @__PURE__ */ new Map();
183207
- let bytesRead = 0;
183208
- const ordered = await Promise.all([...candidates].map(async (path) => {
184013
+ for (const path of scenes) {
184014
+ const code = (await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024)).toString();
184015
+ for (const m of code.matchAll(/["']([^"'\n]+\.(?:svg|png|jpe?g|webp|mp4|mov|webm|wav|mp3|m4a|ogg|woff2?|ttf|otf|js|mjs))["']/gi)) {
184016
+ const child = await locate(m[1], path);
184017
+ if (child) {
184018
+ used.add(child);
184019
+ candidates.add(child);
184020
+ }
184021
+ }
184022
+ }
184023
+ for (const path of [...used]) if (/\/media\/gen\/.*\.(mp4|webm)$/i.test(path)) for (const ext of ["png", "jpg", "webp"]) {
184024
+ const anchor = path.replace(/\.[^.]+$/, "." + ext);
184025
+ if (candidates.has(anchor)) used.add(anchor);
184026
+ }
184027
+ const selected = (p) => used.has(p) || sceneDirs.some((d) => p.startsWith(d + "/") && !lowValue(p));
184028
+ const finalRender = (p) => kind(p) === "video" && /(?:^|\/)(?:out-styles|renders|exports)\//.test(p) && (!sceneDirs.length || sceneDirs.some((d) => p.includes("/" + posix2.basename(d) + "/")) || p.startsWith(prefix + "/"));
184029
+ const resources = [], examples = [], hashes = /* @__PURE__ */ new Map(), duplicatePaths = [];
184030
+ let bytesRead = 0, evidenceBytes = 0;
184031
+ const ordered = await Promise.all([.../* @__PURE__ */ new Set([...candidates, ...scenes])].map(async (path) => {
183209
184032
  try {
183210
- return { path, size: (await lstat2(await checkedPath(root, path, false))).size };
184033
+ return { path, size: (await lstat5(await checkedPath(root, path, false))).size };
183211
184034
  } catch {
183212
184035
  return { path, size: Number.MAX_SAFE_INTEGER };
183213
184036
  }
183214
184037
  }));
183215
- for (const { path, size } of ordered.sort((a, b) => a.size - b.size || a.path.localeCompare(b.path))) try {
184038
+ const priority = (p) => scenes.includes(p) ? 0 : used.has(p) ? 1 : /\/media\/(gen|sfx)\/|logo/i.test(p) && selected(p) ? 2 : finalRender(p) ? 3 : 4;
184039
+ for (const { path, size } of ordered.sort((a, b) => priority(a.path) - priority(b.path) || a.path.localeCompare(b.path))) try {
183216
184040
  if (size === Number.MAX_SAFE_INTEGER) {
183217
184041
  warnings.push(`Resource missing or unsafe: ${path}`);
183218
184042
  continue;
183219
184043
  }
184044
+ if (finalRender(path)) {
184045
+ if (evidenceBytes + size > 2 * 1024 * 1024 * 1024) {
184046
+ warnings.push(`Final render evidence budget (2 GiB): omitted ${path} (${size} bytes).`);
184047
+ continue;
184048
+ }
184049
+ const hash10 = await videoEvidenceHash(await checkedPath(root, path, false), size);
184050
+ evidenceBytes += size;
184051
+ examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, sha256: hash10, evidence: "final_render_local_hash_only", reviewStatus: "unreviewed" });
184052
+ warnings.push(`Final render recorded by hash only; not uploaded: ${path} (${size} bytes).`);
184053
+ continue;
184054
+ }
184055
+ if (lowValue(path) && !used.has(path) || scenes.length && !selected(path)) continue;
184056
+ if (size > 90 * 1024 * 1024) {
184057
+ warnings.push(`Resource exceeds 90 MiB: ${path} (${size} bytes); use a lightweight derivative or explicit requirement.`);
184058
+ continue;
184059
+ }
183220
184060
  if (bytesRead + size > 512 * 1024 * 1024) {
183221
184061
  warnings.push(`Capture byte budget reached; omitted ${path}. Declare it explicitly if needed.`);
183222
184062
  continue;
183223
184063
  }
183224
- safeStyleResourcePath(path);
183225
- if (size > 90 * 1024 * 1024 && kind(path) === "video") {
183226
- const hash9 = await videoEvidenceHash(await checkedPath(root, path, false), size);
183227
- bytesRead += size;
183228
- examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, sha256: hash9, evidence: "local_video_hash_only", reviewStatus: "unreviewed" });
183229
- warnings.push(`Video hashed as local evidence only (over 90 MiB): ${path}. Use a lightweight derivative or explicit requirement for portable resources.`);
184064
+ const bytes = await readReviewFile(await checkedPath(root, path, false), 90 * 1024 * 1024);
184065
+ bytesRead += bytes.length;
184066
+ const hash9 = digest2(bytes), existing = hashes.get(hash9);
184067
+ if (existing) {
184068
+ duplicatePaths.push({ path, resourceId: existing });
183230
184069
  continue;
183231
184070
  }
183232
184071
  if (resources.length >= 200) {
183233
- warnings.push(`Portable manifest limit (200 resources): omitted ${path}; curate explicit dependencies.`);
184072
+ warnings.push(`Portable manifest limit (200 unique resources): omitted ${path}; curate explicit dependencies.`);
183234
184073
  continue;
183235
184074
  }
183236
- const bytes = await readReviewFile(await checkedPath(root, path, false), 90 * 1024 * 1024);
183237
- bytesRead += bytes.length;
183238
- if (bytesRead > 512 * 1024 * 1024) throw new Error("Project capture exceeds 512 MiB; use lightweight review assets.");
183239
- const hash8 = digest2(bytes), rid = `resource-${resources.length + 1}`;
183240
- hashes.set(hash8, rid);
183241
- resources.push({ id: rid, kind: kind(path), purpose: `Candidate from ${posix2.basename(path)}; confirm use and adaptation.`, required: true, source: { type: "local", path, sha256: hash8 } });
183242
- if (kind(path) === "video") examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, evidence: "candidate_video", resourceId: rid, sha256: hash8, reviewStatus: "unreviewed" });
184075
+ const rid = `resource-${resources.length + 1}`;
184076
+ hashes.set(hash9, rid);
184077
+ resources.push({ id: rid, kind: kind(path), purpose: `${used.has(path) ? "Scene dependency" : "Candidate"} from ${posix2.basename(path)}; confirm use and adaptation.`, required: true, source: { type: "local", path, sha256: hash9 } });
183243
184078
  } catch (error) {
183244
- if (error.message.startsWith("Project capture exceeds")) throw error;
183245
- warnings.push(`Resource unavailable or unsupported: ${path}`);
184079
+ warnings.push(`Resource unavailable or unsupported: ${path}: ${error.message}`);
183246
184080
  }
183247
184081
  const beats = jsonFiles.flatMap(({ value }) => Array.isArray(value.beats) ? value.beats : Array.isArray(value.uses) ? value.uses : []);
183248
184082
  for (const [i, b] of beats.entries()) {
@@ -183255,7 +184089,7 @@ async function buildStyleFromProject(root, id3, projectId, name) {
183255
184089
  }
183256
184090
  for (const note of ["direction.md", "review.md"]) {
183257
184091
  const evidence = [];
183258
- for (const path of notes.get(note) ?? []) try {
184092
+ for (const path of (notes.get(note) ?? []).filter((p) => !scenes.length || sceneDirs.includes(posix2.dirname(p)) || roots.includes(posix2.dirname(p)))) try {
183259
184093
  const content = (await readReviewFile(await checkedPath(root, path, false), 96 * 1024)).toString("utf8");
183260
184094
  if (/(?:Bearer\s+\S+|(?:api[_-]?key|access[_-]?token|client[_-]?secret|password)\s*[:=]|-----BEGIN.*PRIVATE KEY)/i.test(content)) {
183261
184095
  warnings.push(`Skipped ${path}: credential-like text needs local redaction.`);
@@ -183279,20 +184113,32 @@ ${content}`;
183279
184113
  }
183280
184114
  files[`${base}/examples.json`] = stableJson({ schemaVersion: 1, id: id3, examples });
183281
184115
  files[`${base}/resources.json`] = stableJson({ schemaVersion: 1, id: id3, resources });
183282
- files[`${base}/provenance.json`] = stableJson({ schemaVersion: 1, id: id3, projectId, brandId: project.brand, projectSha256: digest2(Buffer.from(raw)), scannedRoots, receipts, coverage: "candidate_files_and_declared_intervals", reviewStatus: "unreviewed" });
184116
+ files[`${base}/provenance.json`] = stableJson({ schemaVersion: 1, id: id3, projectId, brandId: project.brand, projectSha256: digest2(Buffer.from(raw)), scannedRoots, scenes, duplicatePaths, receipts, coverage: "candidate_files_and_declared_intervals", reviewStatus: "unreviewed" });
183283
184117
  files[`${base}/techniques.json`] = stableJson({ schemaVersion: 1, id: id3, techniques: [] });
183284
184118
  function receiptEntries(value, depth = 0) {
183285
- if (depth > 4 || !object7(value)) return [];
184119
+ if (depth > 8 || !value || typeof value !== "object") return [];
184120
+ if (Array.isArray(value)) return value.slice(0, 100).flatMap((v2) => receiptEntries(v2, depth + 1));
183286
184121
  return [value, ...Object.values(value).slice(0, 100).flatMap((child) => receiptEntries(child, depth + 1))];
183287
184122
  }
183288
- const promptExamples = jsonFiles.filter((x) => generationReceipt(x.value)).flatMap(({ path, value: rawValue }) => receiptEntries(generationReceipt(rawValue)).flatMap((value) => {
183289
- const prompt = typeof value.prompt === "string" ? value.prompt : typeof value.input?.prompt === "string" ? value.input.prompt : void 0;
183290
- if (!prompt || prompt.length > 8e3 || /(?:https?:\/\/|Bearer\s|api[_-]?key|access[_-]?token|client[_-]?secret|password|-----BEGIN)/i.test(prompt)) {
183291
- if (prompt) warnings.push(`Prompt omitted from ${path}: review it locally before saving.`);
183292
- return [];
183293
- }
183294
- return [{ source: path, prompt, model: typeof value.model === "string" ? value.model : void 0, status: "pilot_example_not_template" }];
183295
- })).slice(0, 100);
184123
+ const promptExamples = [];
184124
+ for (const { path, value } of jsonFiles) for (const node of receiptEntries(value)) {
184125
+ const prompt = typeof node.prompt === "string" ? node.prompt : typeof node.input?.prompt === "string" ? node.input.prompt : void 0;
184126
+ if (!prompt) continue;
184127
+ const locator = [node.outFile, node.outputPath, node.path, node.file, node.output].find((v2) => typeof v2 === "string" && media.test(v2));
184128
+ const output2 = locator ? await locate(locator, path) : void 0;
184129
+ if (!output2 || !used.has(output2)) {
184130
+ warnings.push(`Prompt not linked to selected scene media: ${path}; omitted.`);
184131
+ continue;
184132
+ }
184133
+ if (prompt.length > 8e3 || /(?:https?:\/\/|Bearer\s|api[_-]?key|access[_-]?token|client[_-]?secret|password|-----BEGIN)/i.test(prompt)) {
184134
+ warnings.push(`Prompt omitted from ${path}: review it locally before saving.`);
184135
+ continue;
184136
+ }
184137
+ if (promptExamples.length < 100 && !promptExamples.some((p) => p.outputPath === output2 && p.prompt === prompt)) promptExamples.push({ source: path, outputPath: output2, prompt, ...typeof node.model === "string" && /^[a-zA-Z0-9 ._/-]{1,100}$/.test(node.model) ? { model: node.model } : {}, status: "linked_pilot_example_not_template" });
184138
+ }
184139
+ const ambiguousOutputs = new Set(promptExamples.filter((p) => promptExamples.some((other) => other.outputPath === p.outputPath && other.prompt !== p.prompt)).map((p) => p.outputPath));
184140
+ for (const output2 of ambiguousOutputs) warnings.push(`Conflicting prompts for ${output2}; omitted until output provenance is confirmed.`);
184141
+ for (let i = promptExamples.length - 1; i >= 0; i--) if (ambiguousOutputs.has(promptExamples[i].outputPath)) promptExamples.splice(i, 1);
183296
184142
  while (Buffer.byteLength(stableJson({ schemaVersion: 1, id: id3, examples: promptExamples })) > 110 * 1024) {
183297
184143
  promptExamples.pop();
183298
184144
  if (!warnings.includes("Prompt example budget reached; remaining prompts need local review.")) warnings.push("Prompt example budget reached; remaining prompts need local review.");
@@ -183321,66 +184167,14 @@ Read pilot-direction.md and pilot-review.md when present. Complete: what to pres
183321
184167
  const result2 = validateDocument(path, content);
183322
184168
  if (!result2.valid) throw new Error(result2.issues.map((x) => `${path}: ${x.message}`).join("\n"));
183323
184169
  }
183324
- return { files, warnings };
183325
- }
183326
-
183327
- // packages/cli/src/style-authoring.ts
183328
- import { createHash as createHash2 } from "node:crypto";
183329
- import { constants as constants5 } from "node:fs";
183330
- import { lstat as lstat4, mkdir as mkdir2, open as open5, readdir as readdir3, rmdir, unlink as unlink3 } from "node:fs/promises";
183331
- import { dirname as dirname2 } from "node:path";
183332
-
183333
- // packages/cli/src/workspace-lock.ts
183334
- import { constants as constants4 } from "node:fs";
183335
- import { lstat as lstat3, open as open4, rename as rename2, unlink as unlink2 } from "node:fs/promises";
183336
- import { hostname } from "node:os";
183337
- import { randomUUID as randomUUID2 } from "node:crypto";
183338
- var LOCK_PATH = ".editorbrain-operation.lock";
183339
- async function withWorkspaceLock(root, operation, options = {}) {
183340
- const legacyLock = await checkedPath(root, ".editorharness-operation.lock", false);
183341
- let legacy;
183342
- try {
183343
- legacy = await open4(legacyLock, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY | constants4.O_NOFOLLOW, 384);
183344
- } catch (error) {
183345
- if (error.code === "EEXIST") throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation to finish.");
183346
- throw error;
183347
- }
183348
- try {
183349
- const path = await checkedPath(root, LOCK_PATH, false);
183350
- let handle;
183351
- try {
183352
- handle = await open4(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY | constants4.O_NOFOLLOW, 384);
183353
- } catch (error) {
183354
- if (error.code !== "EEXIST") throw error;
183355
- throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation. If it crashed, verify no process is using the folder before removing .editorbrain-operation.lock. Locks are never removed automatically.");
183356
- }
183357
- const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID2(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
183358
- try {
183359
- await handle.writeFile(owner);
183360
- await handle.close();
183361
- const oldRoot = await checkedPath(root, ".editorharness", false);
183362
- const newRoot = await checkedPath(root, ".editorbrain", false);
183363
- const exists3 = async (path2) => lstat3(path2).then(() => true, (error) => {
183364
- if (error.code === "ENOENT") return false;
183365
- throw error;
183366
- });
183367
- if (options.migrateLegacy !== false && await exists3(oldRoot)) {
183368
- if (await exists3(newRoot)) throw new CliError("WORKSPACE_PATH_CONFLICT", "This folder contains two versions of the workspace directory.", "Reconcile the directories before continuing; neither was changed.");
183369
- await rename2(oldRoot, newRoot);
183370
- }
183371
- return await operation();
183372
- } finally {
183373
- await handle.close().catch(() => {
183374
- });
183375
- if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
183376
- }
183377
- } finally {
183378
- await legacy.close();
183379
- await unlink2(legacyLock);
183380
- }
184170
+ return { files, warnings: [...new Set(warnings)] };
183381
184171
  }
183382
184172
 
183383
184173
  // packages/cli/src/style-authoring.ts
184174
+ import { createHash as createHash5 } from "node:crypto";
184175
+ import { constants as constants8 } from "node:fs";
184176
+ import { lstat as lstat6, mkdir as mkdir4, open as open8, readdir as readdir6, rmdir, unlink as unlink4 } from "node:fs/promises";
184177
+ import { dirname as dirname5 } from "node:path";
183384
184178
  function styleId(id3) {
183385
184179
  try {
183386
184180
  return assertIdentifier(id3);
@@ -183390,7 +184184,7 @@ function styleId(id3) {
183390
184184
  }
183391
184185
  async function exists(path) {
183392
184186
  try {
183393
- await lstat4(path);
184187
+ await lstat6(path);
183394
184188
  return true;
183395
184189
  } catch (error) {
183396
184190
  if (error.code === "ENOENT") return false;
@@ -183419,12 +184213,12 @@ async function makeDirectories(root, path, created) {
183419
184213
  const relative2 = segments.slice(0, i).join("/");
183420
184214
  const target = await checkedPath(root, relative2, false);
183421
184215
  try {
183422
- await mkdir2(target);
183423
- const info = await lstat4(target);
184216
+ await mkdir4(target);
184217
+ const info = await lstat6(target);
183424
184218
  created.push({ path: relative2, dev: info.dev, ino: info.ino });
183425
184219
  } catch (error) {
183426
184220
  if (error.code !== "EEXIST") throw error;
183427
- if (!(await lstat4(await checkedPath(root, relative2, false))).isDirectory()) throw new Error(`Not a directory: ${relative2}`);
184221
+ if (!(await lstat6(await checkedPath(root, relative2, false))).isDirectory()) throw new Error(`Not a directory: ${relative2}`);
183428
184222
  }
183429
184223
  }
183430
184224
  }
@@ -183432,21 +184226,22 @@ async function cleanCreated(root, paths2, directory) {
183432
184226
  for (const item of [...paths2].reverse()) {
183433
184227
  try {
183434
184228
  const target = await checkedPath(root, item.path, false);
183435
- const info = await lstat4(target);
184229
+ const info = await lstat6(target);
183436
184230
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
183437
184231
  if (directory) await rmdir(target);
183438
- else await unlink3(target);
184232
+ else await unlink4(target);
183439
184233
  } catch {
183440
184234
  }
183441
184235
  }
183442
184236
  }
183443
184237
  async function createLocalStyle(options) {
183444
184238
  const id3 = styleId(options.id);
184239
+ if (options.scene && !options.fromProject) throw new Error("--scene requires --from-project; it selects the production scene to capture.");
183445
184240
  if (options.name !== void 0 && (!options.name.trim() || options.name.length > 200 || /[\x00-\x1f\x7f]/.test(options.name))) {
183446
184241
  throw new CliError("INVALID_ARGUMENT", "--name must contain 1\u2013200 characters without control characters.", "Use a short, descriptive style name.");
183447
184242
  }
183448
184243
  const root = await ensureRoot(options.directory, true);
183449
- const seeded = options.fromProject ? await buildStyleFromProject(root, id3, options.fromProject, options.name) : void 0;
184244
+ const seeded = options.fromProject ? await buildStyleFromProject(root, id3, options.fromProject, options.name, options.scene) : void 0;
183450
184245
  const files = seeded?.files ?? createStyle({ id: id3, name: options.name });
183451
184246
  await preflightCreate(root, id3, files);
183452
184247
  return withWorkspaceLock(root, async () => {
@@ -183455,9 +184250,9 @@ async function createLocalStyle(options) {
183455
184250
  const createdDirectories = [];
183456
184251
  try {
183457
184252
  for (const [path, content] of Object.entries(files)) {
183458
- await makeDirectories(root, dirname2(path), createdDirectories);
184253
+ await makeDirectories(root, dirname5(path), createdDirectories);
183459
184254
  const target = await checkedPath(root, path);
183460
- const handle = await open5(target, constants5.O_WRONLY | constants5.O_CREAT | constants5.O_EXCL | constants5.O_NOFOLLOW, 420);
184255
+ const handle = await open8(target, constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL | constants8.O_NOFOLLOW, 420);
183461
184256
  try {
183462
184257
  const info = await handle.stat();
183463
184258
  createdFiles.push({ path, dev: info.dev, ino: info.ino });
@@ -183491,12 +184286,12 @@ async function readStyle(root, id3) {
183491
184286
  try {
183492
184287
  const target = await checkedPath(root, path, false);
183493
184288
  if (!await exists(target)) continue;
183494
- if (!(await lstat4(target)).isDirectory()) {
184289
+ if (!(await lstat6(target)).isDirectory()) {
183495
184290
  issues.push({ path, message: "Style path is not a directory." });
183496
184291
  continue;
183497
184292
  }
183498
184293
  directories.push(path);
183499
- const entries = await readdir3(target, { withFileTypes: true });
184294
+ const entries = await readdir6(target, { withFileTypes: true });
183500
184295
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
183501
184296
  if (!/\.(json|md)$/.test(entry.name)) continue;
183502
184297
  const document2 = `${path}/${entry.name}`;
@@ -183520,19 +184315,19 @@ async function readStyle(root, id3) {
183520
184315
  async function checkLocalResource(root, path, expected) {
183521
184316
  safeStyleResourcePath(path);
183522
184317
  const target = await checkedPath(root, path, false);
183523
- const handle = await open5(target, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
184318
+ const handle = await open8(target, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
183524
184319
  try {
183525
184320
  const before = await handle.stat();
183526
184321
  if (!before.isFile()) throw new Error("Resource is not a regular file.");
183527
184322
  if (!expected) return {};
183528
- const hash8 = createHash2("sha256");
183529
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash8.update(chunk);
184323
+ const hash9 = createHash5("sha256");
184324
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash9.update(chunk);
183530
184325
  const after = await handle.stat();
183531
- const current2 = await lstat4(await checkedPath(root, path, false));
184326
+ const current2 = await lstat6(await checkedPath(root, path, false));
183532
184327
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
183533
184328
  throw new Error("Resource changed while its hash was being checked; check it again.");
183534
184329
  }
183535
- return { actualSha256: hash8.digest("hex") };
184330
+ return { actualSha256: hash9.digest("hex") };
183536
184331
  } finally {
183537
184332
  await handle.close();
183538
184333
  }
@@ -183615,8 +184410,8 @@ async function checkLocalStyle(options) {
183615
184410
 
183616
184411
  // packages/cli/src/style-sync.ts
183617
184412
  var MAX = 90 * 1024 * 1024;
183618
- var digest3 = (bytes) => createHash3("sha256").update(bytes).digest("hex");
183619
- var types = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg", ".html": "application/octet-stream", ".js": "application/octet-stream", ".mjs": "application/octet-stream", ".json": "application/octet-stream", ".woff": "application/octet-stream", ".woff2": "application/octet-stream", ".ttf": "application/octet-stream", ".otf": "application/octet-stream" };
184413
+ var digest3 = (bytes) => createHash6("sha256").update(bytes).digest("hex");
184414
+ var types = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg", ".svg": "application/octet-stream", ".html": "application/octet-stream", ".js": "application/octet-stream", ".mjs": "application/octet-stream", ".json": "application/octet-stream", ".woff": "application/octet-stream", ".woff2": "application/octet-stream", ".ttf": "application/octet-stream", ".otf": "application/octet-stream" };
183620
184415
  function styleResourceWarnings(files) {
183621
184416
  const warnings = [];
183622
184417
  for (const [path, content] of Object.entries(files)) if (/^\.editorbrain\/styles\/[^/]+\/resources.json$/.test(path)) {
@@ -183651,7 +184446,7 @@ async function boundedStyleDownload(response) {
183651
184446
  async function requireCurrentLayout(root) {
183652
184447
  let legacy = false;
183653
184448
  try {
183654
- await lstat5(await checkedPath(root, ".editorharness", false));
184449
+ await lstat7(await checkedPath(root, ".editorharness", false));
183655
184450
  legacy = true;
183656
184451
  } catch (error) {
183657
184452
  if (error.code !== "ENOENT") throw error;
@@ -183672,22 +184467,26 @@ async function pushStyle(client, directory, id3, options = {}) {
183672
184467
  if (!check.valid) throw new CliError("INVALID_STYLE", "Style validation failed.", "Run styles check and correct the reported files.", false, { issues: check.issues });
183673
184468
  const { files } = await readStyle(root, id3), resourcePath = `.editorbrain/styles/${id3}/resources.json`, initial = { ...files };
183674
184469
  const manifest = files[resourcePath] ? JSON.parse(files[resourcePath]) : { schemaVersion: 1, id: id3, resources: [] };
184470
+ const skippedResources = [];
183675
184471
  const uploads = [];
183676
184472
  if (options.withResources) for (const resource of manifest.resources) {
183677
184473
  if (resource.source.type === "requirement") continue;
183678
184474
  if (resource.source.type === "asset") continue;
183679
184475
  const path = resource.source.path, mime = types[posix3.extname(path).toLowerCase()];
183680
- if (!mime) throw new Error(`Unsupported style resource type: ${path}`);
183681
- const bytes = await readReviewFile(await checkedPath(root, path, false), MAX), hash8 = digest3(bytes);
183682
- if (resource.source.sha256 && resource.source.sha256 !== hash8) throw new Error(`Hash mismatch: ${path}`);
184476
+ if (!mime) {
184477
+ skippedResources.push({ id: resource.id, path, reason: "Unsupported file type; retained as a local dependency, not uploaded." });
184478
+ continue;
184479
+ }
184480
+ const bytes = await readReviewFile(await checkedPath(root, path, false), MAX), hash9 = digest3(bytes);
184481
+ if (resource.source.sha256 && resource.source.sha256 !== hash9) throw new Error(`Hash mismatch: ${path}`);
183683
184482
  const ext = posix3.extname(path).toLowerCase(), name = "asset-" + posix3.basename(path, ext).replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 80) + ext;
183684
- uploads.push({ resource, path, hash: hash8, mime, name });
183685
- resource.source = { type: "asset", assetId: hash8, fileName: name, originalPath: path };
184483
+ uploads.push({ resource, path, hash: hash9, mime, name });
184484
+ resource.source = { type: "asset", assetId: hash9, fileName: name, originalPath: path };
183686
184485
  }
183687
184486
  if (options.withResources && files[resourcePath]) files[resourcePath] = stableJson(manifest);
183688
184487
  const preview = await pushWorkspace(client, root, files, { dryRun: true });
183689
184488
  if (preview.conflicts?.length) throw new CliError("SYNC_CONFLICT", "Style changed remotely.", "Reconcile before uploading resources.", false, { conflicts: preview.conflicts });
183690
- if (options.dryRun) return { ...preview, resourcesToUpload: uploads.map((x) => ({ id: x.resource.id, sha256: x.hash, path: x.path })), warnings: styleResourceWarnings(files), mediaUploaded: false };
184489
+ if (options.dryRun) return { ...preview, resourcesToUpload: uploads.map((x) => ({ id: x.resource.id, sha256: x.hash, path: x.path })), skippedResources, warnings: [...styleResourceWarnings(files), ...skippedResources.length ? [`Skipped unsupported resources (still local): ${skippedResources.map((r) => r.path).join(", ")}. Convert them to style documents or explicit local requirements.`] : []], mediaUploaded: false };
183691
184490
  const verified = [];
183692
184491
  for (const upload of uploads) {
183693
184492
  const bytes = await readReviewFile(await checkedPath(root, upload.path, false), MAX);
@@ -183717,7 +184516,7 @@ async function pushStyle(client, directory, id3, options = {}) {
183717
184516
  for (const [path, content] of Object.entries(initial)) if (await readText(root, path) !== content) throw new Error("Style changed locally during upload; reconcile before pushing documents. Uploaded assets remain available.");
183718
184517
  const result2 = await pushWorkspace(client, root, files);
183719
184518
  if (options.withResources && files[resourcePath] !== initial[resourcePath]) await atomicWrite(root, resourcePath, files[resourcePath]);
183720
- return { ...result2, verifiedResources: verified, mediaUploaded: uploads.length > 0, warnings: styleResourceWarnings(files), atomic: false };
184519
+ return { ...result2, verifiedResources: verified, mediaUploaded: uploads.length > 0, skippedResources, warnings: [...styleResourceWarnings(files), ...skippedResources.length ? [`Skipped unsupported resources (still local): ${skippedResources.map((r) => r.path).join(", ")}. Convert them to style documents or explicit local requirements.`] : []], atomic: false };
183721
184520
  }, { migrateLegacy: false });
183722
184521
  }
183723
184522
  async function pullStyle(client, directory, id3, options = {}) {
@@ -183770,10 +184569,10 @@ async function pullStyle(client, directory, id3, options = {}) {
183770
184569
  }
183771
184570
 
183772
184571
  // packages/cli/src/style-operations.ts
183773
- import { createHash as createHash4 } from "node:crypto";
183774
- import { unlink as unlink4, lstat as lstat6, readdir as readdir4 } from "node:fs/promises";
184572
+ import { createHash as createHash7 } from "node:crypto";
184573
+ import { unlink as unlink5, lstat as lstat8, readdir as readdir7 } from "node:fs/promises";
183775
184574
  import { posix as posix4 } from "node:path";
183776
- var hash4 = (bytes) => createHash4("sha256").update(bytes).digest("hex");
184575
+ var hash5 = (bytes) => createHash7("sha256").update(bytes).digest("hex");
183777
184576
  var readJson = async (root, path) => JSON.parse((await readReviewFile(await checkedPath(root, path, false), 1024 * 1024)).toString("utf8"));
183778
184577
  var jsonLiteral = (value) => JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
183779
184578
  async function localStyle(root, id3) {
@@ -183838,7 +184637,7 @@ async function extractComponent(directory, id3, componentId, scene, bindingsFile
183838
184637
  bindingSpans(code, bindings);
183839
184638
  const manifest = JSON.parse(files[base + "resources.json"] ?? stableJson({ schemaVersion: 1, id: id3, resources: [] }));
183840
184639
  if (manifest.resources.some((r) => r.id === resourceId)) throw new Error("Component resource ID already exists.");
183841
- const digest5 = hash4(bytes), destination = `production-assets/styles/${id3}/${componentId}-${digest5}.html`;
184640
+ const digest5 = hash5(bytes), destination = `production-assets/styles/${id3}/${componentId}-${digest5}.html`;
183842
184641
  manifest.resources.push({ id: resourceId, kind: "script", purpose: `Exact source for component ${componentId}. Review dependencies and bindings before reuse.`, required: true, source: { type: "local", path: destination, sha256: digest5 } });
183843
184642
  const style = JSON.parse(files[base + "style.json"]);
183844
184643
  style.components = [...(style.components ?? []).filter((c) => c.id !== componentId), { id: componentId, status: bindings.length ? "implemented" : "concept" }];
@@ -183854,7 +184653,7 @@ async function extractComponent(directory, id3, componentId, scene, bindingsFile
183854
184653
  if (error.code !== "ENOENT") throw error;
183855
184654
  }
183856
184655
  if (previousSource) {
183857
- if (hash4(previousSource) !== digest5) throw new Error("Existing component snapshot was modified.");
184656
+ if (hash5(previousSource) !== digest5) throw new Error("Existing component snapshot was modified.");
183858
184657
  } else await atomicWrite(root, destination, bytes, { document: false, overwrite: false });
183859
184658
  for (const path of Object.keys(changes)) {
183860
184659
  let current2;
@@ -183875,7 +184674,7 @@ async function extractComponent(directory, id3, componentId, scene, bindingsFile
183875
184674
  for (const path of written.reverse()) try {
183876
184675
  if (await readText(root, path) === changes[path]) {
183877
184676
  if (files[path] !== void 0) await atomicWrite(root, path, files[path]);
183878
- else await unlink4(await checkedPath(root, path));
184677
+ else await unlink5(await checkedPath(root, path));
183879
184678
  }
183880
184679
  } catch {
183881
184680
  }
@@ -183898,7 +184697,7 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183898
184697
  const expected = resource.source.type === "asset" ? resource.source.assetId : resource.source.sha256;
183899
184698
  if (!expected) throw new Error("Component source must have a pinned hash.");
183900
184699
  const bytes = await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024);
183901
- if (hash4(bytes) !== expected) throw new Error("Component source SHA-256 mismatch.");
184700
+ if (hash5(bytes) !== expected) throw new Error("Component source SHA-256 mismatch.");
183902
184701
  const code = bytes.toString(), values = await readJson(root, parameters);
183903
184702
  if (!values || Array.isArray(values) || typeof values !== "object" || Object.keys(values).some((k) => !c.bindings.some((b) => b.name === k))) throw new Error(`Parameter object contains unknown bindings: ${values && typeof values === "object" ? Object.keys(values).filter((k) => !c.bindings.some((b) => b.name === k)).join(", ") : "expected an object"}. Expected: ${c.bindings.map((b) => b.name).join(", ")}.`);
183904
184703
  for (const b of c.bindings) {
@@ -183915,9 +184714,9 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183915
184714
  let entries = 0;
183916
184715
  async function inspect(path2, depth = 0) {
183917
184716
  if (depth > 4) throw new Error(`Binding ${b.name}: directory exceeds depth 4.`);
183918
- const absolute = await checkedPath(root, path2, false), info = await lstat6(absolute);
184717
+ const absolute = await checkedPath(root, path2, false), info = await lstat8(absolute);
183919
184718
  if (!info.isDirectory()) throw new Error(`Binding ${b.name}: expected a directory at ${path2}.`);
183920
- for (const item of await readdir4(absolute, { withFileTypes: true })) {
184719
+ for (const item of await readdir7(absolute, { withFileTypes: true })) {
183921
184720
  if (++entries > 500) throw new Error(`Binding ${b.name}: directory exceeds 500 entries.`);
183922
184721
  const child = posix4.join(path2, item.name);
183923
184722
  safeStyleResourcePath(child);
@@ -183937,12 +184736,23 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183937
184736
  }
183938
184737
  prepared += code.slice(cursor);
183939
184738
  const warnings = [];
183940
- const locators = /* @__PURE__ */ new Map();
184739
+ const locators = /* @__PURE__ */ new Map(), locatorResources = /* @__PURE__ */ new Map();
183941
184740
  for (const r of manifest.resources) {
183942
184741
  if (r.source.type === "requirement") continue;
183943
184742
  const original = r.source.type === "local" ? r.source.path : r.source.originalPath;
183944
184743
  if (!original) continue;
183945
184744
  locators.set(original, r.source.type === "local" ? r.source.path : styleAssetPath(id3, r.source));
184745
+ locatorResources.set(original, r);
184746
+ }
184747
+ const provenance = files[base + "provenance.json"] ? JSON.parse(files[base + "provenance.json"]) : void 0;
184748
+ if (Array.isArray(provenance?.duplicatePaths)) for (const alias of provenance.duplicatePaths.slice(0, 2e3)) {
184749
+ safeStyleResourcePath(alias.path);
184750
+ const r = manifest.resources.find((r2) => r2.id === alias.resourceId);
184751
+ if (!r || r.source.type === "requirement") continue;
184752
+ const mapped = r.source.type === "local" ? r.source.path : styleAssetPath(id3, r.source);
184753
+ if (locators.has(alias.path) && locators.get(alias.path) !== mapped) throw new Error("Conflicting duplicate resource alias: " + alias.path);
184754
+ locators.set(alias.path, mapped);
184755
+ locatorResources.set(alias.path, r);
183946
184756
  }
183947
184757
  const replacements = [];
183948
184758
  for (const m of prepared.matchAll(/(?:src\s*=\s*["']|href\s*=\s*["']|url\(["']?)([^"')\s>]+)/g)) {
@@ -183953,16 +184763,16 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183953
184763
  }
183954
184764
  const original = posix4.normalize(posix4.join(posix4.dirname(c.originPath ?? path), value)), mapped = locators.get(original);
183955
184765
  if (mapped) {
183956
- const source2 = manifest.resources.find((r) => r.source.type === "local" ? r.source.path === original : r.source.type === "asset" && r.source.originalPath === original);
184766
+ const source2 = locatorResources.get(original);
183957
184767
  const expected2 = source2.source.type === "asset" ? source2.source.assetId : source2.source.type === "local" ? source2.source.sha256 : void 0;
183958
184768
  const dependency = await readReviewFile(await checkedPath(root, mapped, false), 90 * 1024 * 1024);
183959
- if (expected2 && hash4(dependency) !== expected2) throw new Error("Dependency hash mismatch: " + original);
184769
+ if (expected2 && hash5(dependency) !== expected2) throw new Error("Dependency hash mismatch: " + original);
183960
184770
  replacements.push({ from: m[0], to: m[0].slice(0, -value.length) + posix4.relative(posix4.dirname(out), mapped).split("/").map(encodeURIComponent).join("/") });
183961
184771
  } else warnings.push("Undeclared local dependency: " + original);
183962
184772
  }
183963
184773
  for (const replacement of replacements) prepared = prepared.split(replacement.from).join(replacement.to);
183964
184774
  await atomicWrite(root, out, prepared, { document: false, overwrite: false });
183965
- return { id: id3, componentId, out, sourceSha256: expected, sha256: hash4(Buffer.from(prepared)), rendered: false, warnings: [...new Set(warnings), "Review unbound pilot values and dependencies. This is a code adaptation, not a transfer quality certification."] };
184775
+ return { id: id3, componentId, out, sourceSha256: expected, sha256: hash5(Buffer.from(prepared)), rendered: false, warnings: [...new Set(warnings), "Review unbound pilot values and dependencies. This is a code adaptation, not a transfer quality certification."] };
183966
184776
  }
183967
184777
  async function testStyleTransfer(directory, id3, projectId) {
183968
184778
  const root = await ensureRoot(directory);
@@ -184002,15 +184812,24 @@ async function testStyleTransfer(directory, id3, projectId) {
184002
184812
  }
184003
184813
  async function prepareCaptions(directory, projectId, file, out, styleId2) {
184004
184814
  const root = await ensureRoot(directory);
184005
- assertIdentifier(projectId);
184815
+ if (projectId) assertIdentifier(projectId);
184006
184816
  safeStyleResourcePath(out);
184007
184817
  if (!out.endsWith(".html")) throw new Error("--out must be a new HTML file.");
184008
- let files = await readProjectWorkspace(root, projectId);
184009
- if (styleId2) {
184010
- const candidate = await localStyle(root, styleId2), path = `videos/${projectId}/project.json`;
184011
- files = { ...files, ...candidate.files, [path]: stableJson({ ...JSON.parse(files[path]), style: styleId2 }) };
184818
+ let files, resolved;
184819
+ if (projectId) {
184820
+ files = await readProjectWorkspace(root, projectId);
184821
+ if (styleId2) {
184822
+ const candidate = await localStyle(root, styleId2), path = `videos/${projectId}/project.json`;
184823
+ files = { ...files, ...candidate.files, [path]: stableJson({ ...JSON.parse(files[path]), style: styleId2 }) };
184824
+ }
184825
+ resolved = await resolveProject(files, projectId);
184826
+ } else {
184827
+ if (!styleId2) throw new Error("Provide --project ID for resolved brand preferences or --style ID for a standalone preset preview.");
184828
+ files = (await localStyle(root, styleId2)).files;
184829
+ const base = `.editorbrain/styles/${styleId2}/`;
184830
+ resolved = { project: { style: styleId2 }, styleProduction: { captions: files[base + "captions.json"] ? JSON.parse(files[base + "captions.json"]) : void 0 }, styleResources: files[base + "resources.json"] ? JSON.parse(files[base + "resources.json"]) : void 0, output: { width: 1080, height: 1920 }, warnings: ["Standalone 1080\xD71920 preset preview; no project or brand preferences applied. Use --project for the final edit."] };
184012
184831
  }
184013
- const resolved = await resolveProject(files, projectId), preset = resolved.styleProduction?.captions;
184832
+ const preset = resolved.styleProduction?.captions;
184014
184833
  if (!preset) throw new Error(`Style ${resolved.project.style} has no captions.json preset.`);
184015
184834
  const cues = validateCaptionCues(await readJson(root, file));
184016
184835
  let fontDataUrl;
@@ -184021,7 +184840,7 @@ async function prepareCaptions(directory, projectId, file, out, styleId2) {
184021
184840
  if (!resource || resource.kind !== "font" || resource.source.type === "requirement") throw new Error("Caption font resource is missing; declare and download the exact font.");
184022
184841
  const path = resource.source.type === "local" ? resource.source.path : styleAssetPath(resolved.project.style, resource.source), expected = resource.source.type === "local" ? resource.source.sha256 : resource.source.assetId;
184023
184842
  const bytes = await readReviewFile(await checkedPath(root, path, false), 8 * 1024 * 1024);
184024
- if (!expected || hash4(bytes) !== expected) throw new Error("Caption font needs a verified SHA-256.");
184843
+ if (!expected || hash5(bytes) !== expected) throw new Error("Caption font needs a verified SHA-256.");
184025
184844
  const ext = posix4.extname(path).slice(1);
184026
184845
  if (!["woff", "woff2", "ttf", "otf"].includes(ext)) throw new Error("Unsupported caption font format.");
184027
184846
  fontDataUrl = `data:font/${ext};base64,${bytes.toString("base64")}`;
@@ -184031,14 +184850,14 @@ async function prepareCaptions(directory, projectId, file, out, styleId2) {
184031
184850
  }
184032
184851
 
184033
184852
  // packages/cli/src/style-sources.ts
184034
- import { constants as constants6 } from "node:fs";
184035
- import { open as open7, mkdir as mkdir4, writeFile, rm } from "node:fs/promises";
184036
- import { dirname as dirname4 } from "node:path";
184853
+ import { constants as constants9 } from "node:fs";
184854
+ import { open as open10, mkdir as mkdir6, writeFile, rm } from "node:fs/promises";
184855
+ import { dirname as dirname7 } from "node:path";
184037
184856
 
184038
184857
  // packages/cli/src/authored-motion.ts
184039
- import { lstat as lstat7, mkdir as mkdir3, open as open6, link as link2, unlink as unlink5 } from "node:fs/promises";
184040
- import { dirname as dirname3, join as join2 } from "node:path";
184041
- import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
184858
+ import { lstat as lstat9, mkdir as mkdir5, open as open9, link as link2, unlink as unlink6 } from "node:fs/promises";
184859
+ import { dirname as dirname6, join as join3 } from "node:path";
184860
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
184042
184861
  async function downloadAuthoredSource(client, pin, root, out, fetcher = fetch) {
184043
184862
  return downloadPinnedSource(client, pin, root, out, "motion", fetcher);
184044
184863
  }
@@ -184048,7 +184867,7 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
184048
184867
  if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(pin.id) || !/^\d+\.\d+\.\d+$/.test(pin.version) || !/^[a-f0-9]{64}$/.test(pin.sha256) || !Number.isSafeInteger(pin.bytes) || pin.bytes < 1 || pin.bytes > (kind2 === "style" ? 128 : pin.version === "1.4.0" ? 96 : 16) * 1024 * 1024) throw new CliError("INVALID_ARGUMENT", "Invalid pinned source bundle.", "Retrieve one authored scene from the catalog.");
184049
184868
  const target = await checkedPath(root, out, false);
184050
184869
  try {
184051
- await lstat7(target);
184870
+ await lstat9(target);
184052
184871
  throw new CliError("FILE_EXISTS", "The output already exists.", "Choose a new archive path.");
184053
184872
  } catch (error) {
184054
184873
  if (error.code !== "ENOENT") throw error;
@@ -184067,23 +184886,23 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
184067
184886
  if (!response.ok) throw new CliError("DOWNLOAD_FAILED", `Source download failed (HTTP ${response.status}).`, "Request a new source link; existing archives were preserved.");
184068
184887
  const reader = response.body?.getReader();
184069
184888
  if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
184070
- const temporary = join2(dirname3(target), `.eb-motion-${randomUUID3()}.tmp`);
184889
+ const temporary = join3(dirname6(target), `.eb-motion-${randomUUID4()}.tmp`);
184071
184890
  let handle;
184072
- const hash8 = createHash5("sha256");
184891
+ const hash9 = createHash8("sha256");
184073
184892
  let size = 0;
184074
184893
  try {
184075
- await mkdir3(dirname3(target), { recursive: true });
184894
+ await mkdir5(dirname6(target), { recursive: true });
184076
184895
  await checkedPath(root, out, false);
184077
- handle = await open6(temporary, "wx", 384);
184896
+ handle = await open9(temporary, "wx", 384);
184078
184897
  for (; ; ) {
184079
184898
  const { done, value } = await reader.read();
184080
184899
  if (done) break;
184081
184900
  size += value.length;
184082
184901
  if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
184083
- hash8.update(value);
184902
+ hash9.update(value);
184084
184903
  await handle.writeFile(value);
184085
184904
  }
184086
- if (size !== pin.bytes || hash8.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
184905
+ if (size !== pin.bytes || hash9.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
184087
184906
  await handle.sync();
184088
184907
  await handle.close();
184089
184908
  await checkedPath(root, out, false);
@@ -184095,18 +184914,18 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
184095
184914
  } finally {
184096
184915
  await handle?.close().catch(() => {
184097
184916
  });
184098
- await unlink5(temporary).catch(() => {
184917
+ await unlink6(temporary).catch(() => {
184099
184918
  });
184100
184919
  }
184101
184920
  return { ...kind2 === "style" ? { documents: metadata.documents } : {}, id: pin.id, version: pin.version, path: target, sha256: pin.sha256, bytes: size, extracted: false, executed: false, rendered: false, next: kind2 === "style" ? "Use editorbrain styles prepare with this exact version and archive to create a guarded local copy. Nothing has been extracted or executed." : "Inspect bundle README and selected card; extract into a new local directory. Bind current project colors, fonts, language, content, timing and sound before rendering. The demo is not your finished edit." };
184102
184921
  }
184103
184922
 
184104
184923
  // packages/cli/src/style-archive.ts
184105
- import { createHash as createHash6 } from "node:crypto";
184924
+ import { createHash as createHash9 } from "node:crypto";
184106
184925
  import { gunzipSync } from "node:zlib";
184107
184926
  var STYLE_ARCHIVE_MAX_BYTES = 128 * 1024 * 1024;
184108
184927
  var STYLE_UNPACKED_MAX_BYTES = 192 * 1024 * 1024;
184109
- var archiveHash = (bytes) => createHash6("sha256").update(bytes).digest("hex");
184928
+ var archiveHash = (bytes) => createHash9("sha256").update(bytes).digest("hex");
184110
184929
  function safeArchivePath(name) {
184111
184930
  if (!name || name.length > 240 || !/^[a-zA-Z0-9_. /-]+$/.test(name) || name.startsWith("/") || name.split("/").some((p) => !p || p === "." || p === "..")) throw new Error("Unsafe archive path");
184112
184931
  return name;
@@ -185191,7 +186010,7 @@ async function downloadStyle(client, id3, version, root, out) {
185191
186010
  async function prepareStyleSource(root, id3, version, file, out) {
185192
186011
  const selected = getStyleSource(id3, version), guard = styleSourceGuards[id3];
185193
186012
  if (!selected || !guard) throw new Error("This CLI cannot prepare the exact style version. Update EditorBrain; no version was substituted.");
185194
- const input = await checkedPath(root, file, false), handle = await open7(input, constants6.O_RDONLY | constants6.O_NOFOLLOW);
186013
+ const input = await checkedPath(root, file, false), handle = await open10(input, constants9.O_RDONLY | constants9.O_NOFOLLOW);
185195
186014
  let bytes;
185196
186015
  try {
185197
186016
  const stat = await handle.stat();
@@ -185226,13 +186045,13 @@ Un render de demo no certifica transferencia. Revisa el video completo y registr
185226
186045
  files.set("PROJECT-BINDING.md", Buffer.from(guide));
185227
186046
  files.set("PROJECT-BINDING.json", Buffer.from(JSON.stringify(receipt, null, 2) + "\n"));
185228
186047
  const target = await checkedPath(root, out, false);
185229
- await mkdir4(dirname4(target), { recursive: true });
186048
+ await mkdir6(dirname7(target), { recursive: true });
185230
186049
  await checkedPath(root, out, false);
185231
- await mkdir4(target, { mode: 448 });
186050
+ await mkdir6(target, { mode: 448 });
185232
186051
  try {
185233
186052
  for (const [name, data] of files) {
185234
186053
  const destination = await checkedPath(target, name, false);
185235
- await mkdir4(dirname4(destination), { recursive: true });
186054
+ await mkdir6(dirname7(destination), { recursive: true });
185236
186055
  await writeFile(destination, data, { flag: "wx", mode: 384 });
185237
186056
  }
185238
186057
  } catch (error) {
@@ -185353,335 +186172,7 @@ async function teamCommand(client, subcommand, flags) {
185353
186172
 
185354
186173
  // packages/cli/src/personal-resources.ts
185355
186174
  import { basename, extname as extname2, resolve as resolve3 } from "node:path";
185356
- import { randomUUID as randomUUID4 } from "node:crypto";
185357
-
185358
- // packages/cli/src/media-runtime.ts
185359
- import { spawn } from "node:child_process";
185360
- import { createHash as createHash7 } from "node:crypto";
185361
- import { constants as constants7 } from "node:fs";
185362
- import { lstat as lstat8, open as open8, realpath as realpath2 } from "node:fs/promises";
185363
- import { dirname as dirname5, extname, parse, resolve as resolve2 } from "node:path";
185364
- var MediaToolError = class extends CliError {
185365
- constructor(code, message) {
185366
- super(code, message, code === "MEDIA_TOOL_NOT_FOUND" ? "Install FFmpeg/FFprobe separately and make them available on PATH; no account or model is needed." : "Review the local input and reported limit. An incomplete check does not validate the media.");
185367
- this.name = "MediaToolError";
185368
- }
185369
- };
185370
- var SUPPORTED_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
185371
- ".mp4",
185372
- ".mov",
185373
- ".m4v",
185374
- ".mkv",
185375
- ".webm",
185376
- ".avi",
185377
- ".mpg",
185378
- ".mpeg",
185379
- ".mts",
185380
- ".m2ts",
185381
- ".ts",
185382
- ".ogv",
185383
- ".wmv",
185384
- ".wav",
185385
- ".mp3",
185386
- ".m4a",
185387
- ".aac",
185388
- ".flac",
185389
- ".ogg",
185390
- ".opus",
185391
- ".aif",
185392
- ".aiff",
185393
- ".ac3",
185394
- ".eac3",
185395
- ".jpg",
185396
- ".jpeg",
185397
- ".png",
185398
- ".webp",
185399
- ".bmp",
185400
- ".tif",
185401
- ".tiff",
185402
- ".gif",
185403
- ".avif",
185404
- ".heic",
185405
- ".heif"
185406
- ]);
185407
- var PROTOCOLS = "file,pipe";
185408
- var FORMATS = "mov,matroska,webm,avi,mpeg,mpegts,ogg,wav,flac,mp3,aac,aiff,ac3,eac3,asf,jpeg_pipe,png_pipe,webp_pipe,bmp_pipe,tiff_pipe,gif,heif,avif";
185409
- var DEFAULT_TIMEOUT = 3e4;
185410
- var DEFAULT_OUTPUT_LIMIT = 2 * 1024 * 1024;
185411
- function resolveLocalMediaPath(value) {
185412
- if (!value || value.includes("\0") || /[\r\n]/.test(value) || /^[a-z][a-z\d+.-]*:/i.test(value) && !(process.platform === "win32" && /^[a-z]:[\\/]/i.test(value)) || value.startsWith("\\\\")) {
185413
- throw new MediaToolError("MEDIA_LOCAL_PATH_REQUIRED", "Provide a local filesystem path, not a URL, protocol or network share.");
185414
- }
185415
- return resolve2(value);
185416
- }
185417
- async function assertNoMediaSymlinks(value) {
185418
- const path = resolveLocalMediaPath(value);
185419
- let cursor = path;
185420
- while (cursor !== parse(cursor).root) {
185421
- const info = await lstat8(cursor);
185422
- if (info.isSymbolicLink()) {
185423
- const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath2(cursor) === `/private${cursor}`;
185424
- if (!systemAlias) throw new MediaToolError("MEDIA_SYMLINK", "Symlink media paths are not followed. Use the original local path.");
185425
- }
185426
- cursor = dirname5(cursor);
185427
- }
185428
- return path;
185429
- }
185430
- async function assertLocalMediaFile(value) {
185431
- const path = await assertNoMediaSymlinks(value);
185432
- const info = await lstat8(path);
185433
- if (!info.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
185434
- if (!SUPPORTED_MEDIA_EXTENSIONS.has(extname(path).toLowerCase())) throw new MediaToolError("MEDIA_FORMAT_UNSUPPORTED", "This file extension is not supported for local media inspection.");
185435
- return path;
185436
- }
185437
- function localInputArgs(path) {
185438
- return ["-protocol_whitelist", PROTOCOLS, "-format_whitelist", FORMATS, "-i", resolveLocalMediaPath(path)];
185439
- }
185440
- async function runMediaTool(tool, args, options = {}) {
185441
- if (tool !== "ffmpeg" && tool !== "ffprobe") throw new MediaToolError("MEDIA_TOOL_INVALID", "Unsupported media executable.");
185442
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
185443
- const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_OUTPUT_LIMIT;
185444
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 6e4 || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > 16 * 1024 * 1024) {
185445
- throw new MediaToolError("MEDIA_TOOL_LIMITS_INVALID", "Media runtime limits are outside the supported range.");
185446
- }
185447
- if (!Array.isArray(args) || args.length > 200 || args.some((arg) => typeof arg !== "string" || arg.length > 8192 || arg.includes("\0"))) {
185448
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Invalid media tool arguments.");
185449
- }
185450
- for (let i = 0; i < args.length; i++) {
185451
- const arg = args[i];
185452
- if (/(?:^|[=,;\s])(?:https?|ftp|sftp|tcp|udp|rtsp|rtmp|smb|data|concat|subfile|crypto):/i.test(arg) || arg === "-safe" && args[i + 1] === "0" || arg === "-enable_drefs" && args[i + 1] !== "0") {
185453
- throw new MediaToolError("MEDIA_REMOTE_INPUT_FORBIDDEN", "Only self-contained local media inputs are allowed.");
185454
- }
185455
- if (arg === "-protocol_whitelist" && args[i + 1] !== PROTOCOLS || arg === "-format_whitelist" && args[i + 1] !== FORMATS) {
185456
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "The local media allowlists cannot be widened.");
185457
- }
185458
- if (arg === "-i") {
185459
- await assertLocalMediaFile(args[i + 1] ?? "");
185460
- if (args[i - 4] !== "-protocol_whitelist" || args[i - 3] !== PROTOCOLS || args[i - 2] !== "-format_whitelist" || args[i - 1] !== FORMATS) {
185461
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Every media input must use localInputArgs.");
185462
- }
185463
- }
185464
- }
185465
- return new Promise((resolveResult, reject) => {
185466
- const stdout = [], stderr = [];
185467
- let size = 0, done = false;
185468
- const child = spawn(tool, ["-hide_banner", ...tool === "ffmpeg" ? ["-nostdin"] : [], ...args], { shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
185469
- const fail3 = (error) => {
185470
- if (done) return;
185471
- done = true;
185472
- clearTimeout(timer);
185473
- child.kill("SIGKILL");
185474
- reject(error);
185475
- };
185476
- const timer = setTimeout(() => fail3(new MediaToolError("MEDIA_TOOL_TIMEOUT", "The local media check exceeded its time limit. No complete result is available.")), timeoutMs);
185477
- const collect = (target) => (chunk) => {
185478
- if (done) return;
185479
- size += chunk.length;
185480
- if (size > maxOutputBytes) return fail3(new MediaToolError("MEDIA_TOOL_OUTPUT_LIMIT", "The local media check exceeded its output limit. No complete result is available."));
185481
- target.push(chunk);
185482
- };
185483
- child.stdout.on("data", collect(stdout));
185484
- child.stderr.on("data", collect(stderr));
185485
- child.on("error", (error) => fail3(new MediaToolError(error.code === "ENOENT" ? "MEDIA_TOOL_NOT_FOUND" : "MEDIA_TOOL_FAILED", error.code === "ENOENT" ? `${tool} is not installed or available on PATH. Install it separately to use local media checks.` : "The local media executable could not run.")));
185486
- child.on("close", (code) => {
185487
- if (done) return;
185488
- done = true;
185489
- clearTimeout(timer);
185490
- if (code !== 0) return reject(new MediaToolError("MEDIA_TOOL_FAILED", "The local media tool could not inspect or decode this input. No complete result is available."));
185491
- resolveResult({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
185492
- });
185493
- });
185494
- }
185495
- var finite2 = (value) => {
185496
- if (typeof value !== "number" && typeof value !== "string" || value === "") return null;
185497
- const n = Number(value);
185498
- return Number.isFinite(n) ? n : null;
185499
- };
185500
- var nonnegative2 = (value) => {
185501
- const n = finite2(value);
185502
- return n !== null && n >= 0 ? n : null;
185503
- };
185504
- var positiveInteger = (value) => {
185505
- const n = finite2(value);
185506
- return n !== null && Number.isInteger(n) && n > 0 ? n : void 0;
185507
- };
185508
- var rate2 = (value) => {
185509
- if (typeof value !== "string" || !/^\d+(?:\/\d+)?$/.test(value)) return null;
185510
- const [n, d = "1"] = value.split("/");
185511
- const result2 = Number(n) / Number(d);
185512
- return Number.isFinite(result2) && result2 > 0 ? result2 : null;
185513
- };
185514
- var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
185515
- function hasDisplayTransform(stream) {
185516
- const rotate = stream.tags?.rotate;
185517
- if (rotate !== void 0 && (!Number.isFinite(Number(rotate)) || Number(rotate) % 360 !== 0)) return true;
185518
- const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : [];
185519
- return sideData.some((data) => {
185520
- if (!data || typeof data !== "object") return false;
185521
- if (data.rotation !== void 0 && (!Number.isFinite(Number(data.rotation)) || Number(data.rotation) % 360 !== 0)) return true;
185522
- if (data.displaymatrix === void 0) return data.side_data_type === "Display Matrix";
185523
- if (typeof data.displaymatrix !== "string") return true;
185524
- const values = data.displaymatrix.trim().split("\n").flatMap((line) => line.replace(/^[^:]*:/, "").trim().split(/\s+/).map(Number));
185525
- const identity = [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824];
185526
- return values.length !== 9 || values.some((value, index) => value !== identity[index]);
185527
- });
185528
- }
185529
- async function probeLocalMedia(value) {
185530
- const path = await assertLocalMediaFile(value);
185531
- const handle = await open8(path, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
185532
- try {
185533
- const before = await handle.stat();
185534
- if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
185535
- const entries = "format=duration,start_time:stream=index,codec_type,codec_name,width,height,avg_frame_rate,sample_rate,channels,duration,color_transfer,sample_aspect_ratio,pix_fmt:stream_disposition=attached_pic:stream_side_data=side_data_type,rotation,displaymatrix:stream_tags=rotate";
185536
- const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
185537
- const hash8 = createHash7("sha256");
185538
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash8.update(chunk);
185539
- const after = await handle.stat();
185540
- await assertNoMediaSymlinks(path);
185541
- const current2 = await lstat8(path);
185542
- if (!sameFile(before, after) || !sameFile(after, current2)) throw new MediaToolError("MEDIA_FILE_CHANGED", "The media file changed while it was being inspected. Retry with a stable source.");
185543
- let raw;
185544
- try {
185545
- raw = JSON.parse(stdout);
185546
- } catch {
185547
- throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid metadata.");
185548
- }
185549
- if (!raw || !Array.isArray(raw.streams) || raw.streams.length > 256 || raw.streams.some((stream) => !stream || typeof stream !== "object" || Array.isArray(stream))) throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid or excessive stream metadata.");
185550
- const streams = raw.streams.map((stream, offset) => {
185551
- const type = typeof stream.codec_type === "string" && /^(video|audio|subtitle|data|attachment|unknown)$/.test(stream.codec_type) ? stream.codec_type : "unknown";
185552
- const codec = typeof stream.codec_name === "string" && /^[a-zA-Z0-9_]{1,64}$/.test(stream.codec_name) ? stream.codec_name : null;
185553
- const index = finite2(stream.index);
185554
- return {
185555
- index: index !== null && Number.isInteger(index) && index >= 0 ? index : offset,
185556
- type,
185557
- codec,
185558
- durationSeconds: nonnegative2(stream.duration),
185559
- ...type === "video" ? { displayTransformed: hasDisplayTransform(stream), width: positiveInteger(stream.width), height: positiveInteger(stream.height), fps: rate2(stream.avg_frame_rate), ...typeof stream.sample_aspect_ratio === "string" ? { sampleAspectRatio: stream.sample_aspect_ratio } : {}, ...typeof stream.pix_fmt === "string" ? { pixelFormat: stream.pix_fmt } : {}, ...typeof stream.color_transfer === "string" ? { colorTransfer: stream.color_transfer } : {}, attachedPicture: stream.disposition?.attached_pic === 1 } : {},
185560
- ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
185561
- };
185562
- });
185563
- return { path, sha256: hash8.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
185564
- } finally {
185565
- await handle.close();
185566
- }
185567
- }
185568
-
185569
- // packages/cli/src/production-output.ts
185570
- import { constants as constants8 } from "node:fs";
185571
- import { mkdir as mkdir5, open as open9 } from "node:fs/promises";
185572
- import { dirname as dirname6 } from "node:path";
185573
- async function productionOutputPath(root, relativePath) {
185574
- if (!relativePath.startsWith(".editorbrain-local/") || relativePath.split(/[\\/]/).some((p) => !p || p === ".." || p === ".") || /[\\\x00-\x1f\x7f]/.test(relativePath)) {
185575
- throw new CliError("LOCAL_OUTPUT_REQUIRED", "Production output must be inside .editorbrain-local/.", "Use --out .editorbrain-local/<project>/inventory.json, or omit --out for JSON stdout. These reports are not synced.");
185576
- }
185577
- return checkedPath(root, relativePath, false);
185578
- }
185579
- async function prepareSampleDirectory(root, path) {
185580
- const target = await productionOutputPath(root, path);
185581
- await mkdir5(dirname6(target), { recursive: true });
185582
- await productionOutputPath(root, path);
185583
- return target;
185584
- }
185585
- async function readProductionJson(root, path) {
185586
- const target = await checkedPath(root, path, false);
185587
- const handle = await open9(target, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
185588
- try {
185589
- const stat = await handle.stat();
185590
- if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new CliError("INVALID_REPORT", "Expected a regular JSON file of at most 16 MiB.", "Select a local inventory, plan or check profile.");
185591
- return JSON.parse(await handle.readFile("utf8"));
185592
- } finally {
185593
- await handle.close();
185594
- }
185595
- }
185596
- async function saveProductionReport(root, path, report) {
185597
- const target = await productionOutputPath(root, path);
185598
- if (!path.endsWith(".json")) throw new CliError("INVALID_ARGUMENT", "Report output needs a .json extension.", "Use a new path under .editorbrain-local/.");
185599
- await atomicWrite(root, path, stableJson(report), { document: false, overwrite: false, mode: 384 });
185600
- return target;
185601
- }
185602
- function summarizeProductionReport(value) {
185603
- const r = value;
185604
- const base = { schemaVersion: r.schemaVersion, kind: r.kind, summary: true, mediaUploaded: false, quality: "not_assessed" };
185605
- if (r.kind === "editorbrain.media-inventory") return {
185606
- ...base,
185607
- complete: r.complete,
185608
- contentReviewed: false,
185609
- counts: { assets: r.assets.length, failures: r.failures.length, skipped: r.skipped.length },
185610
- assets: r.assets.slice(0, 8),
185611
- failures: r.failures.slice(0, 5),
185612
- omitted: { assets: Math.max(0, r.assets.length - 8), failures: Math.max(0, r.failures.length - 5), skipped: r.skipped.length },
185613
- next: "Inspect selected source content. Use media sample for specific frames. Read the saved report or rerun with --details for omitted metadata; no content was reviewed automatically."
185614
- };
185615
- if (r.kind === "editorbrain.media-samples") return { ...base, sourceSha256: r.source.sha256, frames: r.frames, contentReviewed: false, next: "View these frames to inspect composition. They do not prove motion or sound." };
185616
- if (r.kind === "editorbrain.production-plan-check") return {
185617
- ...base,
185618
- valid: r.valid,
185619
- inventoryComplete: r.inventoryComplete,
185620
- observations: r.observations,
185621
- sourceFilesReverified: false,
185622
- counts: { sources: r.coverage.length, findings: r.findings.length, repeatedPairs: r.repeatedPairs ?? 0 },
185623
- findings: [...r.findings].sort((a, b) => ({ error: 0, warning: 1, info: 2 })[a.severity] - { error: 0, warning: 1, info: 2 }[b.severity]).slice(0, 8),
185624
- omittedFindings: Math.max(0, r.findings.length - 8),
185625
- next: "Review source reuse and inspection gaps in the saved report. Observations are agent-declared, not independently certified."
185626
- };
185627
- if (r.kind === "editorbrain.render-check") return {
185628
- ...base,
185629
- complete: r.complete,
185630
- technicalStatus: r.technicalStatus,
185631
- file: r.file,
185632
- checks: r.checks,
185633
- findings: r.findings.slice(0, 8),
185634
- findingsSummary: r.findingsSummary,
185635
- omittedFindings: Math.max(0, r.findings.length - 8),
185636
- next: "Reconcile technical candidates with the brief; inspect the actual video/audio. Technical checks do not assess narrative, aesthetics or SFX audibility."
185637
- };
185638
- if (r.kind === "editorbrain.media-source-search") return {
185639
- ...base,
185640
- complete: r.complete,
185641
- results: r.results.slice(0, 5).map((item) => ({ provider: item.provider, id: item.id.slice(0, 180), title: item.title.slice(0, 180), sourceUrl: item.sourceUrl.length <= 1500 ? item.sourceUrl : null, author: item.author?.slice(0, 120) ?? null, license: { id: item.license.id, reason: item.license.reason, url: item.license.url && item.license.url.length <= 500 ? item.license.url : null }, contentReviewed: false, rightsVerified: false })),
185642
- metadataAbbreviated: true,
185643
- failures: r.failures.slice(0, 5),
185644
- counts: r.counts,
185645
- omitted: { results: Math.max(0, r.results.length - 5), failures: Math.max(0, r.failures.length - 5) },
185646
- searchExhaustive: false,
185647
- rightsVerified: false,
185648
- next: "Inspect relevant source pages and media. These archives supplement web image/video search; empty results do not prove absence on the internet."
185649
- };
185650
- if (r.kind === "editorbrain.evidence-check") return {
185651
- ...base,
185652
- valid: r.valid,
185653
- inventoryComplete: r.inventoryComplete,
185654
- observations: r.observations,
185655
- sourceFilesReverified: false,
185656
- factualTruth: "not_assessed",
185657
- reuseRights: "not_assessed",
185658
- findings: r.findings.slice(0, 8),
185659
- omitted: { findings: Math.max(0, r.findings.length - 8) }
185660
- };
185661
- if (r.kind === "editorbrain.audio-check") return {
185662
- ...base,
185663
- complete: r.complete,
185664
- technicalStatus: r.technicalStatus,
185665
- file: r.file,
185666
- fileStable: r.fileStable,
185667
- coverage: r.coverage,
185668
- measurements: r.measurements.slice(0, 8),
185669
- errorCode: r.errorCode,
185670
- creativeQuality: r.creativeQuality,
185671
- omitted: { measurements: Math.max(0, r.measurements.length - 8) },
185672
- next: "Measurements describe this exact file. Listen for intelligibility, pronunciation, SFX and sync when the modality is available."
185673
- };
185674
- if (r.kind === "editorbrain.motion-review") return {
185675
- ...base,
185676
- samples: r.samples ? { frameCount: r.samples.frameCount, fps: r.samples.fps, radiusFrames: r.samples.radiusFrames, samples: r.samples.samples.slice(0, 12), omittedSamples: Math.max(0, r.samples.samples.length - 12) } : null,
185677
- geometryReviews: r.geometryReviews.slice(0, 3).map((g) => ({ scope: g.scope, status: g.status, candidates: g.candidates.slice(0, 8), omittedCandidates: Math.max(0, g.candidates.length - 8), checks: g.checks })),
185678
- omittedGeometryReviews: Math.max(0, r.geometryReviews.length - 3),
185679
- next: "This plans samples and checks declared boxes only. Render/view those frames; read saved details for omitted candidates and intentional overlaps."
185680
- };
185681
- throw new CliError("INVALID_REPORT", "Unknown production report kind.", "Use media inventory/sample or production check/plan-check.");
185682
- }
185683
-
185684
- // packages/cli/src/personal-resources.ts
186175
+ import { randomUUID as randomUUID5 } from "node:crypto";
185685
186176
  var mimeTypes = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".m4v": "video/mp4", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".wav": "audio/wav", ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".flac": "audio/flac", ".ogg": "audio/ogg" };
185686
186177
  var fail = (message) => {
185687
186178
  throw new CliError("INVALID_RESOURCE", message, "Read editorbrain help and references/personal-resources.md. No upload or paid analysis is automatic.");
@@ -185722,7 +186213,7 @@ async function registerLocalResource(client, root, file, options = {}) {
185722
186213
  } while (!existing && after);
185723
186214
  if (existing) break;
185724
186215
  }
185725
- const id3 = existing?.id ?? randomUUID4();
186216
+ const id3 = existing?.id ?? randomUUID5();
185726
186217
  const result2 = existing ? await client.request("/v1/resources/" + id3) : await client.request("/v1/resources/" + id3, { method: "PUT", body: { resource, expectedRevision: 0 } });
185727
186218
  const me = await client.request("/v1/me");
185728
186219
  const namespace = (await sha256(client.url + "\n" + me.workspaceId)).slice(0, 32), path = `.editorbrain-local/resources/${namespace}/${id3}.json`;
@@ -185813,19 +186304,65 @@ async function personalResourceCommand(client, root, command, arg, flags) {
185813
186304
 
185814
186305
  // packages/cli/src/update.ts
185815
186306
  import { execFile } from "node:child_process";
185816
- import { lstat as lstat11, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
186307
+ import { lstat as lstat12, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
185817
186308
  import { homedir as homedir2 } from "node:os";
185818
- import { delimiter, dirname as dirname7, join as join5, resolve as resolve5 } from "node:path";
186309
+ import { delimiter, dirname as dirname8, join as join6, resolve as resolve5 } from "node:path";
185819
186310
  import { promisify } from "node:util";
185820
186311
 
185821
186312
  // packages/cli/src/agent-guidance.ts
185822
- import { createHash as createHash8 } from "node:crypto";
185823
- import { constants as constants9 } from "node:fs";
185824
- import { lstat as lstat9, open as open10, readdir as readdir5, rename as rename3 } from "node:fs/promises";
186313
+ import { createHash as createHash10 } from "node:crypto";
186314
+ import { constants as constants10 } from "node:fs";
186315
+ import { lstat as lstat10, open as open11, readdir as readdir8, rename as rename4 } from "node:fs/promises";
185825
186316
  import { fileURLToPath } from "node:url";
185826
186317
 
185827
186318
  // packages/cli/src/agent-guidance-history.ts
185828
186319
  var VERIFIED_GUIDANCE_RELEASES = [
186320
+ {
186321
+ "version": "0.42.1",
186322
+ "archiveSha256": "a768618052ef4c9b9b1709b5d42644555ca9a95f3a8b1a88096e8a21f285ea69",
186323
+ "files": {
186324
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
186325
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
186326
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
186327
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
186328
+ "editorbrain-motion/SKILL.md": "57292f3a48cc8f1fc2d89f2cc054a3ceabeda9422958fa708f273c662867d5ae",
186329
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
186330
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
186331
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
186332
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
186333
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
186334
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
186335
+ "editorbrain/SKILL.md": "028e66a96eb6fd2382387472727ee1f55ab113a3109917eda57050f8544fde9d",
186336
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
186337
+ "editorbrain/references/cli-mcp.md": "2c34ed7f896865e71959562bcc61b5a34292d6a9a4c14690f0c28d00875da75c",
186338
+ "editorbrain/references/editorial-evidence.md": "79ed5bd90eb903014313c32a1e337822c5cb454e642bcfa852dcb77d30a9392e",
186339
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
186340
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
186341
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
186342
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
186343
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
186344
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
186345
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
186346
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
186347
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
186348
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
186349
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
186350
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
186351
+ "editorbrain/references/onboarding.md": "b842dac368455b670543d9a0defdad91708c10788d1474ddfa6b31ca929e930b",
186352
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
186353
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
186354
+ "editorbrain/references/production-continuity.md": "4b020f5bab47f6b5619387b623339602b87202fec03d85a7a26737209e0b5d4e",
186355
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
186356
+ "editorbrain/references/search-brief.md": "1bd2514f961522675047910f001f33da035382e48e933bc5eadb9d7d01455a0d",
186357
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
186358
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
186359
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
186360
+ "editorbrain/references/studio.md": "673377f4534d9a5edd15a75f1ba9acb589458904dfc34332c30033e03801b6a8",
186361
+ "editorbrain/references/style-creator.md": "cf21325adcf0593b229af78505e3d055550a9af149009512590d99dccd8dcb30",
186362
+ "editorbrain/references/style-source.md": "983fa21b4606c3cdc41b2fa4386ddc8f77a1b14ae782aad8774c000696c14de1",
186363
+ "editorbrain/references/workspace-files.md": "9ded0de75ccbbd0ed382b48c0ccaa6bc9ba1e37613fe47cd0c95a36dffd7e601"
186364
+ }
186365
+ },
185829
186366
  {
185830
186367
  "version": "0.42.0",
185831
186368
  "archiveSha256": "ecd32addc5532a06e23730f2b861ba43c06e006c38250da11ace63c5aa67e7a1",
@@ -186624,8 +187161,8 @@ function bundledSkillDirectory(moduleUrl = import.meta.url, skillName = "editorb
186624
187161
  }
186625
187162
  async function readBytes(root, path) {
186626
187163
  const target = await checkedPath(root, path, false);
186627
- if (!(await lstat9(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
186628
- const handle = await open10(target, constants9.O_RDONLY | constants9.O_NOFOLLOW);
187164
+ if (!(await lstat10(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
187165
+ const handle = await open11(target, constants10.O_RDONLY | constants10.O_NOFOLLOW);
186629
187166
  try {
186630
187167
  if (!(await handle.stat()).isFile()) throw new Error(`Not a regular file: ${path}`);
186631
187168
  return await handle.readFile();
@@ -186646,7 +187183,7 @@ async function loadSkill(directory) {
186646
187183
  const files = /* @__PURE__ */ new Map();
186647
187184
  async function walk(path = "") {
186648
187185
  const location2 = path ? await checkedPath(root, path, false) : root;
186649
- const entries = await readdir5(location2, { withFileTypes: true });
187186
+ const entries = await readdir8(location2, { withFileTypes: true });
186650
187187
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
186651
187188
  const child = path ? `${path}/${entry.name}` : entry.name;
186652
187189
  if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed in bundled skill: ${child}`);
@@ -186702,7 +187239,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
186702
187239
  for (const selected of agents) {
186703
187240
  const to = destinations[selected].directory, from = to.replace(/editorbrain$/, "editorharness");
186704
187241
  const oldPath = await checkedPath(root, from, false), newPath = await checkedPath(root, to, false);
186705
- const exists3 = async (path) => lstat9(path).then(() => true, (error) => {
187242
+ const exists3 = async (path) => lstat10(path).then(() => true, (error) => {
186706
187243
  if (error.code === "ENOENT") return false;
186707
187244
  throw error;
186708
187245
  });
@@ -186720,12 +187257,12 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
186720
187257
  await loadSkill(await checkedPath(root, migration.from, false));
186721
187258
  const target = await checkedPath(root, migration.to, false);
186722
187259
  try {
186723
- await lstat9(target);
187260
+ await lstat10(target);
186724
187261
  throw new Error("Skill destination appeared during migration; no overwrite allowed.");
186725
187262
  } catch (error) {
186726
187263
  if (error.code !== "ENOENT") throw error;
186727
187264
  }
186728
- await rename3(await checkedPath(root, migration.from, false), target);
187265
+ await rename4(await checkedPath(root, migration.from, false), target);
186729
187266
  }
186730
187267
  for (const file of files) {
186731
187268
  let status;
@@ -186735,7 +187272,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
186735
187272
  } catch (error) {
186736
187273
  if (error.code !== "EEXIST") throw error;
186737
187274
  const existing = await readBytes(root, file.path);
186738
- const existingHash = createHash8("sha256").update(existing).digest("hex");
187275
+ const existingHash = createHash10("sha256").update(existing).digest("hex");
186739
187276
  const pristine = file.kind === "skill" && (previousHashesBySkill[file.skillName][file.relativePath]?.includes(existingHash) || isVerifiedHistoricalGuidance(file.skillName, file.relativePath, existingHash));
186740
187277
  const oldPointer = Buffer.from(file.content.toString().replaceAll("/skills/editorbrain/", "/skills/editorharness/"));
186741
187278
  if (!existing.equals(file.content) && (pristine || file.kind === "entryPoint" && existing.equals(oldPointer))) {
@@ -186772,18 +187309,18 @@ async function installAgentGuidance(directory, agent = "both") {
186772
187309
  }
186773
187310
 
186774
187311
  // packages/cli/src/skill-installations.ts
186775
- import { createHash as createHash9, randomUUID as randomUUID5 } from "node:crypto";
186776
- import { readFile as readFile2, readdir as readdir6 } from "node:fs/promises";
187312
+ import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
187313
+ import { readFile as readFile2, readdir as readdir9 } from "node:fs/promises";
186777
187314
  import { homedir } from "node:os";
186778
- import { isAbsolute, join as join4 } from "node:path";
187315
+ import { isAbsolute, join as join5 } from "node:path";
186779
187316
 
186780
187317
  // packages/cli/src/doctor.ts
186781
187318
  import { readFile } from "node:fs/promises";
186782
187319
  import { resolve as resolve4 } from "node:path";
186783
187320
 
186784
187321
  // packages/cli/src/integrations.ts
186785
- import { constants as constants10 } from "node:fs";
186786
- import { lstat as lstat10, open as open11 } from "node:fs/promises";
187322
+ import { constants as constants11 } from "node:fs";
187323
+ import { lstat as lstat11, open as open12 } from "node:fs/promises";
186787
187324
  function object8(value) {
186788
187325
  return value !== null && typeof value === "object" && !Array.isArray(value);
186789
187326
  }
@@ -186816,13 +187353,13 @@ async function readIntegrationSettings(file) {
186816
187353
  const invalidFile = () => new CliError("INVALID_ARGUMENT", "Choose a regular integration settings JSON file under 16 KiB.", "Store provider credentials in the provider connection, not this file.");
186817
187354
  const changedFile = () => new CliError("INVALID_ARGUMENT", "Integration settings changed while being read.", "Choose a stable regular settings file and try again.");
186818
187355
  const limit = 16 * 1024;
186819
- const before = await lstat10(file);
187356
+ const before = await lstat11(file);
186820
187357
  if (!before.isFile() || before.isSymbolicLink() || before.size > limit) throw invalidFile();
186821
187358
  const unchanged2 = (info) => info.isFile() && !info.isSymbolicLink() && info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
186822
- const handle = await open11(file, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
187359
+ const handle = await open12(file, constants11.O_RDONLY | constants11.O_NOFOLLOW | constants11.O_NONBLOCK);
186823
187360
  try {
186824
187361
  const opened = await handle.stat();
186825
- const current2 = await lstat10(file);
187362
+ const current2 = await lstat11(file);
186826
187363
  if (!unchanged2(opened) || !unchanged2(current2)) throw changedFile();
186827
187364
  const bytes = Buffer.alloc(limit + 1);
186828
187365
  let length = 0;
@@ -186832,7 +187369,7 @@ async function readIntegrationSettings(file) {
186832
187369
  length += bytesRead;
186833
187370
  }
186834
187371
  const after = await handle.stat();
186835
- const finalPath = await lstat10(file);
187372
+ const finalPath = await lstat11(file);
186836
187373
  if (length > limit || length !== opened.size || !unchanged2(after) || !unchanged2(finalPath)) throw changedFile();
186837
187374
  try {
186838
187375
  return JSON.parse(bytes.subarray(0, length).toString("utf8"));
@@ -187040,10 +187577,10 @@ async function diagnose(options, fetcher = fetch, probeTool = probe) {
187040
187577
 
187041
187578
  // packages/cli/src/skill-installations.ts
187042
187579
  function installationRegistry() {
187043
- return join4(process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join4(homedir(), ".config", "editorbrain"), "skill-installations");
187580
+ return join5(process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join5(homedir(), ".config", "editorbrain"), "skill-installations");
187044
187581
  }
187045
187582
  function recordName(directory, scope) {
187046
- return createHash9("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
187583
+ return createHash11("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
187047
187584
  }
187048
187585
  function validateRecord(value) {
187049
187586
  const r = value;
@@ -187071,7 +187608,7 @@ async function listInstallations(registry = installationRegistry()) {
187071
187608
  if (error.code === "ENOENT") return [];
187072
187609
  throw error;
187073
187610
  }
187074
- const names = (await readdir6(root)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort();
187611
+ const names = (await readdir9(root)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort();
187075
187612
  if (names.length > 1e3) throw new Error("Too many registered installations. Update a specific directory.");
187076
187613
  const records = [];
187077
187614
  for (const name of names) {
@@ -187107,7 +187644,7 @@ async function installManagedGuidance(directory, agent, options = {}) {
187107
187644
  const previous = await readInstallation(root, scope, options.registry);
187108
187645
  if (previous?.pinned) throw new CliError("SKILLS_PINNED", "Las instrucciones de este proyecto est\xE1n fijadas.", "Usa skill unpin en esta carpeta cuando termines la edici\xF3n.");
187109
187646
  const target = parseAgentTarget(agent ?? previous?.agent);
187110
- const install = await prepareAgentGuidance(root, target, void 0, void 0, { global: options.global, backupId: randomUUID5() });
187647
+ const install = await prepareAgentGuidance(root, target, void 0, void 0, { global: options.global, backupId: randomUUID6() });
187111
187648
  const result2 = await install();
187112
187649
  try {
187113
187650
  await rememberGuidance(result2, scope, options.registry);
@@ -187128,7 +187665,7 @@ async function pinGuidance(directory, pinned, registry = installationRegistry())
187128
187665
  for (const agent of record13.agent === "both" ? ["codex", "claude"] : [record13.agent]) {
187129
187666
  for (const skill of BUNDLED_SKILLS) for (const path of await bundledGuidanceFiles(skill)) {
187130
187667
  const current2 = await readText(root, `${installedSkillDirectory(agent, skill)}/${path}`, false);
187131
- const expected = await readFile2(join4(bundledSkillDirectory(void 0, skill), path), "utf8");
187668
+ const expected = await readFile2(join5(bundledSkillDirectory(void 0, skill), path), "utf8");
187132
187669
  if (current2 !== expected) throw new Error("Project instructions differ from this release; resolve them before pinning.");
187133
187670
  }
187134
187671
  }
@@ -187174,18 +187711,18 @@ async function latestPublishedVersion(fetcher = fetch) {
187174
187711
  }
187175
187712
  }
187176
187713
  async function npmEntrypoint(env = process.env) {
187177
- const candidates = [env.npm_execpath, join5(dirname7(process.execPath), "node_modules/npm/bin/npm-cli.js")];
187714
+ const candidates = [env.npm_execpath, join6(dirname8(process.execPath), "node_modules/npm/bin/npm-cli.js")];
187178
187715
  for (const directory of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
187179
- candidates.push(join5(directory, "node_modules/npm/bin/npm-cli.js"));
187716
+ candidates.push(join6(directory, "node_modules/npm/bin/npm-cli.js"));
187180
187717
  try {
187181
- candidates.push(await realpath3(join5(directory, "npm")));
187718
+ candidates.push(await realpath3(join6(directory, "npm")));
187182
187719
  } catch {
187183
187720
  }
187184
187721
  }
187185
187722
  for (const candidate of candidates) {
187186
187723
  if (!candidate || !candidate.endsWith("npm-cli.js")) continue;
187187
187724
  try {
187188
- if ((await lstat11(candidate)).isFile()) return candidate;
187725
+ if ((await lstat12(candidate)).isFile()) return candidate;
187189
187726
  } catch {
187190
187727
  }
187191
187728
  }
@@ -187219,9 +187756,9 @@ async function installPublishedCli(version, runner = exec) {
187219
187756
  );
187220
187757
  }
187221
187758
  try {
187222
- const metadata = JSON.parse(await readFile3(join5(root, "editorbrain/package.json"), "utf8"));
187759
+ const metadata = JSON.parse(await readFile3(join6(root, "editorbrain/package.json"), "utf8"));
187223
187760
  if (metadata.name !== "editorbrain" || metadata.version !== version || metadata.bin?.editorbrain !== "bin/editorbrain.mjs") throw new Error("Unexpected installed package");
187224
- const executable = join5(root, "editorbrain/bin/editorbrain.mjs");
187761
+ const executable = join6(root, "editorbrain/bin/editorbrain.mjs");
187225
187762
  const result2 = JSON.parse((await runner(process.execPath, [executable, "version"], { timeout: 15e3, maxBuffer: 65536 })).stdout);
187226
187763
  if (result2.version !== version) throw new Error("Unexpected executable version");
187227
187764
  return executable;
@@ -187256,7 +187793,7 @@ async function detectAgents(root) {
187256
187793
  for (const skill of BUNDLED_SKILLS) {
187257
187794
  const file = await checkedPath(root, `${installedSkillDirectory(agent, skill)}/SKILL.md`, false);
187258
187795
  try {
187259
- if ((await lstat11(file)).isFile()) {
187796
+ if ((await lstat12(file)).isFile()) {
187260
187797
  found.push(agent);
187261
187798
  break;
187262
187799
  }
@@ -187442,8 +187979,8 @@ async function projectProgressCommand(client, command, flags) {
187442
187979
  }
187443
187980
 
187444
187981
  // packages/cli/src/event-mix.ts
187445
- import { mkdir as mkdir6, readFile as readFile4, writeFile as writeFile2, unlink as unlink6 } from "node:fs/promises";
187446
- import { dirname as dirname8, join as join6, resolve as resolve6 } from "node:path";
187982
+ import { mkdir as mkdir7, readFile as readFile4, writeFile as writeFile2, unlink as unlink7 } from "node:fs/promises";
187983
+ import { dirname as dirname9, join as join7, resolve as resolve6 } from "node:path";
187447
187984
  function validateEventCues(value, duration) {
187448
187985
  const v = value;
187449
187986
  if (!v || v.schemaVersion !== 1 || v.clock !== "output_seconds" || !Array.isArray(v.cues) || v.cues.length > 300 || Object.keys(v).some((k) => !["schemaVersion", "clock", "cues"].includes(k))) throw new Error("Use schemaVersion 1, clock output_seconds and up to 300 explicit cues.");
@@ -187482,7 +188019,7 @@ function floats(bytes) {
187482
188019
  async function decode(file, target) {
187483
188020
  await runMediaTool("ffmpeg", ["-v", "error", "-n", ...localInputArgs(file), "-map", "0:a:0", "-vn", "-ar", "48000", "-ac", "2", "-f", "f32le", target], { timeoutMs: 6e5 });
187484
188021
  const b = await readFile4(target);
187485
- await unlink6(target);
188022
+ await unlink7(target);
187486
188023
  return floats(b);
187487
188024
  }
187488
188025
  function wav(data) {
@@ -187518,12 +188055,12 @@ async function mixEvents(options) {
187518
188055
  sources.push(source2);
187519
188056
  }
187520
188057
  const directory = await productionOutputPath(options.root, options.out);
187521
- await mkdir6(dirname8(directory), { recursive: true, mode: 448 });
188058
+ await mkdir7(dirname9(directory), { recursive: true, mode: 448 });
187522
188059
  await productionOutputPath(options.root, options.out);
187523
- await mkdir6(directory, { mode: 448 });
187524
- const mix = await decode(voice.path, join6(directory, "voice.raw")), records = [];
188060
+ await mkdir7(directory, { mode: 448 });
188061
+ const mix = await decode(voice.path, join7(directory, "voice.raw")), records = [];
187525
188062
  for (let i = 0; i < cues.length; i++) {
187526
- const effect = await decode(sources[i].path, join6(directory, "effect.raw"));
188063
+ const effect = await decode(sources[i].path, join7(directory, "effect.raw"));
187527
188064
  records.push({ ...cues[i], sourceSha256: sources[i].sha256, sampleFrames: effect.length / 2, ...addEventPcm(mix, effect, cues[i].time, cues[i].peak) });
187528
188065
  }
187529
188066
  const cuePlan = { durationSeconds: mix.length / 2 / 48e3, hookEndSeconds, cues: records.map((c) => {
@@ -187540,16 +188077,16 @@ async function mixEvents(options) {
187540
188077
  if (peak >= 0.99) throw new Error("Mix would clip: lower explicit cue levels or prepare voice gain first. No automatic voice normalization applied.");
187541
188078
  for (const s of [voice, ...sources]) if ((await probeLocalMedia(s.path)).sha256 !== s.sha256) throw new Error("Audio source changed during mix.");
187542
188079
  if (options.context && !await options.context.validateContext()) throw new Error("Project preferences changed during the mix. Refresh context; no final mix was written.");
187543
- const path = join6(directory, "mix.wav");
188080
+ const path = join7(directory, "mix.wav");
187544
188081
  await writeFile2(path, wav(mix), { flag: "wx", mode: 384 });
187545
188082
  const report = { schemaVersion: 1, kind: "editorbrain.event-mix", voiceSha256: voice.sha256, path, clock: "output_seconds", musicAdded: false, voiceGain: 1, cues: records, peak, mediaUploaded: false, listening: "not_assessed", preferenceCheck, contextScope: options.context?.contextScope ?? "not_checked", contextHash: options.context?.contextVersion ?? null, note: "The SFX maximum peak is aligned to the event, not its file start. Inspect audible attack and sync; those can differ from the peak. Without --project, preferences are not checked; do not claim compliance." };
187546
- await writeFile2(join6(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
188083
+ await writeFile2(join7(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
187547
188084
  return report;
187548
188085
  }
187549
188086
 
187550
188087
  // packages/cli/src/production-sheet.ts
187551
- import { mkdir as mkdir7, readFile as readFile5, writeFile as writeFile3, unlink as unlink7 } from "node:fs/promises";
187552
- import { dirname as dirname9, join as join7 } from "node:path";
188088
+ import { mkdir as mkdir8, readFile as readFile5, writeFile as writeFile3, unlink as unlink8 } from "node:fs/promises";
188089
+ import { dirname as dirname10, join as join8 } from "node:path";
187553
188090
  var esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
187554
188091
  function freezeIntervals(log, duration) {
187555
188092
  const result2 = [];
@@ -187588,13 +188125,13 @@ async function createProductionSheet(options) {
187588
188125
  if (options.platform && input.platform && options.platform !== input.platform) throw new Error("Platform flag conflicts with review profile.");
187589
188126
  const platform = options.platform ?? input.platform;
187590
188127
  const directory = await productionOutputPath(options.root, options.out);
187591
- await mkdir7(dirname9(directory), { recursive: true, mode: 448 });
188128
+ await mkdir8(dirname10(directory), { recursive: true, mode: 448 });
187592
188129
  await productionOutputPath(options.root, options.out);
187593
- await mkdir7(directory, { mode: 448 });
187594
- const raw = join7(directory, "samples.gray");
187595
- const result2 = await runMediaTool("ffmpeg", ["-v", "info", "-nostats", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-filter_complex", `[0:${video[0].index}]split=2[a][b];[a]freezedetect=n=0.003:d=1,fps=fps=1:start_time=0:round=up,scale=240:240:force_original_aspect_ratio=decrease,setsar=1[thumb];[b]fps=fps=1:start_time=0:round=up,scale=96:96,format=gray[gray]`, "-map", "[thumb]", "-an", "-fps_mode", "passthrough", "-q:v", "3", join7(directory, "frame-%05d.jpg"), "-map", "[gray]", "-an", "-f", "rawvideo", raw], { timeoutMs: 6e5, maxOutputBytes: 8 * 1024 * 1024 });
188130
+ await mkdir8(directory, { mode: 448 });
188131
+ const raw = join8(directory, "samples.gray");
188132
+ const result2 = await runMediaTool("ffmpeg", ["-v", "info", "-nostats", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-filter_complex", `[0:${video[0].index}]split=2[a][b];[a]freezedetect=n=0.003:d=1,fps=fps=1:start_time=0:round=up,scale=240:240:force_original_aspect_ratio=decrease,setsar=1[thumb];[b]fps=fps=1:start_time=0:round=up,scale=96:96,format=gray[gray]`, "-map", "[thumb]", "-an", "-fps_mode", "passthrough", "-q:v", "3", join8(directory, "frame-%05d.jpg"), "-map", "[gray]", "-an", "-f", "rawvideo", raw], { timeoutMs: 6e5, maxOutputBytes: 8 * 1024 * 1024 });
187596
188133
  const data = await readFile5(raw);
187597
- await unlink7(raw);
188134
+ await unlink8(raw);
187598
188135
  const count = data.length / (96 * 96);
187599
188136
  if (!Number.isInteger(count) || count < 1 || count > 1801 || count < Math.ceil(duration - 1e-6)) throw new Error("Incomplete frame sampling; no complete review was accepted.");
187600
188137
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new Error("Source changed during review.");
@@ -187608,15 +188145,15 @@ async function createProductionSheet(options) {
187608
188145
  return `<figure><div class="frame"><img loading="lazy" src="frame-${String(i + 1).padStart(5, "0")}.jpg" alt="${i} segundos">${p ? `<i class="bottom"></i><i class="right"></i>` : ""}</div><figcaption>${i}s ${esc(warnings.join(" \xB7 "))}</figcaption></figure>`;
187609
188146
  }).join("");
187610
188147
  const html = `<!doctype html><html lang="es"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' file:; style-src 'unsafe-inline'"><title>EditorBrain \xB7 revisi\xF3n completa</title><style>body{background:#171717;color:#eee;font:15px system-ui;margin:28px}main{display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:15px}figure{margin:0}.frame{position:relative;display:table}img{display:block;max-width:100%;height:auto}i{position:absolute;background:#f4474760;pointer-events:none}.bottom{bottom:0;left:0;width:100%;height:${(p?.bottom ?? 0) * 100}%}.right{top:0;right:0;height:100%;width:${(p?.right ?? 0) * 100}%}figcaption{padding:8px 0;min-height:40px;color:#ffd280}p{max-width:850px}</style><h1>Revisi\xF3n del video completo</h1><p>${count} cuadros \xB7 1 por segundo. ${esc(platform ?? "Sin perfil social")} \xB7 rojo: riesgo de interfaz aproximado. Las pausas planeadas se excluyen de avisos de congelaci\xF3n. Geometr\xEDa: ${esc(report.geometryStatus)}. Esto no aprueba la edici\xF3n.</p><p>Sin OCR ni detecci\xF3n autom\xE1tica de logos. Revisa la reproducci\xF3n y los cuadros adyacentes a cada aviso. Informe: report.json.</p><main>${cards}</main></html>`;
187611
- await writeFile3(join7(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
187612
- await writeFile3(join7(directory, "index.html"), html, { flag: "wx", mode: 384 });
187613
- return { kind: report.kind, complete: true, path: join7(directory, "index.html"), reportPath: join7(directory, "report.json"), sourceSha256: source2.sha256, frames: count, candidates: { freezes: freezes.length, nearlyEmpty: flat.length, geometry: report.candidates.geometry.length }, geometryStatus: report.geometryStatus, creativeQuality: "not_assessed", mediaUploaded: false };
188148
+ await writeFile3(join8(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
188149
+ await writeFile3(join8(directory, "index.html"), html, { flag: "wx", mode: 384 });
188150
+ return { kind: report.kind, complete: true, path: join8(directory, "index.html"), reportPath: join8(directory, "report.json"), sourceSha256: source2.sha256, frames: count, candidates: { freezes: freezes.length, nearlyEmpty: flat.length, geometry: report.candidates.geometry.length }, geometryStatus: report.geometryStatus, creativeQuality: "not_assessed", mediaUploaded: false };
187614
188151
  }
187615
188152
 
187616
188153
  // packages/cli/src/presenter-matte.ts
187617
188154
  import { spawn as spawn2 } from "node:child_process";
187618
- import { mkdir as mkdir8, writeFile as writeFile4, rename as rename4, unlink as unlink8 } from "node:fs/promises";
187619
- import { dirname as dirname10, join as join8 } from "node:path";
188155
+ import { mkdir as mkdir9, writeFile as writeFile4, rename as rename5, unlink as unlink9 } from "node:fs/promises";
188156
+ import { dirname as dirname11, join as join9 } from "node:path";
187620
188157
 
187621
188158
  // packages/cli/src/presenter-matte-source.ts
187622
188159
  var presenterMatteSource = 'import Foundation\nimport AVFoundation\nimport Vision\nimport CoreImage\nfunc fail(_ message: String) -> Never { fputs(message + "\\n", stderr); exit(1) }\nlet a = CommandLine.arguments\nif a.count != 5 { fail("Expected source, new output, width and height") }\nlet src = URL(fileURLWithPath:a[1]), dst = URL(fileURLWithPath:a[2])\nguard let w = Int(a[3]), let h = Int(a[4]), w > 0, h > 0 else { fail("Invalid dimensions") }\nif FileManager.default.fileExists(atPath:dst.path) { fail("Output already exists") }\nlet asset = AVURLAsset(url:src)\nguard let track = asset.tracks(withMediaType:.video).first else { fail("No video") }\nlet tr = track.preferredTransform\nif abs(tr.b) > 0.001 || abs(tr.c) > 0.001 || tr.a < 0 || tr.d < 0 { fail("Normalize orientation before segmentation") }\nlet reader = try AVAssetReader(asset:asset)\nlet output = AVAssetReaderTrackOutput(track:track,outputSettings:[kCVPixelBufferPixelFormatTypeKey as String:kCVPixelFormatType_32BGRA])\nreader.add(output)\nlet writer = try AVAssetWriter(outputURL:dst,fileType:.mov)\nlet input = AVAssetWriterInput(mediaType:.video,outputSettings:[AVVideoCodecKey:AVVideoCodecType.h264,AVVideoWidthKey:w,AVVideoHeightKey:h,AVVideoCompressionPropertiesKey:[AVVideoAverageBitRateKey:4000000]])\nlet adapter = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput:input,sourcePixelBufferAttributes:[kCVPixelBufferPixelFormatTypeKey as String:kCVPixelFormatType_32BGRA,kCVPixelBufferWidthKey as String:w,kCVPixelBufferHeightKey as String:h,kCVPixelBufferIOSurfacePropertiesKey as String:[:]])\nwriter.add(input)\nif !writer.startWriting() || !reader.startReading() { fail("Cannot start media processing") }\nlet request = VNGeneratePersonSegmentationRequest()\nrequest.qualityLevel = .accurate\nrequest.outputPixelFormat = kCVPixelFormatType_OneComponent8\nlet context = CIContext(options:[.cacheIntermediates:false])\nvar count = 0\nvar origin: CMTime? = nil\nwhile let sb = output.copyNextSampleBuffer() {\n autoreleasepool {\n let sourcePTS = CMSampleBufferGetPresentationTimeStamp(sb)\n if origin == nil { origin = sourcePTS; writer.startSession(atSourceTime:.zero) }\n let pts = CMTimeSubtract(sourcePTS,origin!)\n guard let pb = CMSampleBufferGetImageBuffer(sb) else { fail("Missing input frame") }\n do { try VNImageRequestHandler(cvPixelBuffer:pb,orientation:.up).perform([request]) }\n catch { fail("Segmentation failed; no placeholder was inserted") }\n guard let mask = request.results?.first?.pixelBuffer else { fail("No segmentation result; no placeholder was inserted") }\n let ci = CIImage(cvPixelBuffer:mask)\n let scaled = ci.transformed(by:CGAffineTransform(scaleX:CGFloat(w)/ci.extent.width,y:CGFloat(h)/ci.extent.height))\n let deadline = Date().addingTimeInterval(30)\n while !input.isReadyForMoreMediaData {\n if writer.status == .failed || Date() > deadline { fail("Writer stalled") }\n Thread.sleep(forTimeInterval:0.002)\n }\n guard let pool = adapter.pixelBufferPool else { fail("No pixel buffer pool") }\n var buf:CVPixelBuffer?\n if CVPixelBufferPoolCreatePixelBuffer(nil,pool,&buf) != kCVReturnSuccess || buf == nil { fail("Cannot allocate output frame") }\n context.render(scaled,to:buf!)\n if !adapter.append(buf!,withPresentationTime:pts) { fail("Cannot append output frame") }\n count += 1\n }\n}\nif reader.status != .completed || count == 0 { fail("Incomplete source decode") }\ninput.markAsFinished()\nlet group = DispatchGroup(); group.enter(); writer.finishWriting { group.leave() }\nif group.wait(timeout:.now()+60) != .success || writer.status != .completed { fail("Incomplete output") }\nprint("{\\"frames\\":\\(count),\\"fullMontage\\":true}")\n';
@@ -187678,10 +188215,10 @@ async function generatePresenterMatte(options) {
187678
188215
  const video = videos[0], plan = planPresenterMatte(source2.durationSeconds, video.fps);
187679
188216
  if (video.width > 2160 || video.height > 2160 || video.width % 2 || video.height % 2) throw new Error("Normalize montage dimensions: even width and height up to 2160.");
187680
188217
  const dir = await productionOutputPath(options.root, options.out);
187681
- await mkdir8(dirname10(dir), { recursive: true, mode: 448 });
188218
+ await mkdir9(dirname11(dir), { recursive: true, mode: 448 });
187682
188219
  await productionOutputPath(options.root, options.out);
187683
- await mkdir8(dir, { mode: 448 });
187684
- const swift = join8(dir, "matte.swift"), binary = join8(dir, "matte-tool"), result2 = join8(dir, "matte.partial.mov");
188220
+ await mkdir9(dir, { mode: 448 });
188221
+ const swift = join9(dir, "matte.swift"), binary = join9(dir, "matte-tool"), result2 = join9(dir, "matte.partial.mov");
187685
188222
  await writeFile4(swift, presenterMatteSource, { flag: "wx", mode: 384 });
187686
188223
  try {
187687
188224
  await runLocal("swiftc", ["-O", swift, "-o", binary], 12e4);
@@ -187689,21 +188226,21 @@ async function generatePresenterMatte(options) {
187689
188226
  const [clock, matteClock, mask, after] = await Promise.all([readFrameClock(source2.path), readFrameClock(result2), probeLocalMedia(result2), probeLocalMedia(source2.path)]);
187690
188227
  assertMatteClocks(clock, matteClock);
187691
188228
  if (after.sha256 !== source2.sha256) throw new Error("Source changed during segmentation.");
187692
- const finalPath = join8(dir, "matte.mov");
187693
- await rename4(result2, finalPath);
188229
+ const finalPath = join9(dir, "matte.mov");
188230
+ await rename5(result2, finalPath);
187694
188231
  mask.path = finalPath;
187695
188232
  const report = { ...plan, generated: true, engine: "apple-vision-local", source: source2, matte: mask, frames: clock.length, frameClockVerified: true, placeholderFramesInserted: 0, silhouetteQuality: "not_assessed", mediaUploaded: false, modelDownloads: false, note: "Run review-sheet --matte on the result and inspect silhouette edges in motion. A blank mask can mean no person or a missed detection." };
187696
- await writeFile4(join8(dir, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
188233
+ await writeFile4(join9(dir, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
187697
188234
  return report;
187698
188235
  } finally {
187699
- await unlink8(binary).catch(() => {
188236
+ await unlink9(binary).catch(() => {
187700
188237
  });
187701
188238
  }
187702
188239
  }
187703
188240
 
187704
188241
  // packages/cli/src/sfx.ts
187705
- import { readdir as readdir7, lstat as lstat12 } from "node:fs/promises";
187706
- import { join as join9, extname as extname3, basename as basename2 } from "node:path";
188242
+ import { readdir as readdir10, lstat as lstat13 } from "node:fs/promises";
188243
+ import { join as join10, extname as extname3, basename as basename2 } from "node:path";
187707
188244
 
187708
188245
  // packages/cli/src/production-context.ts
187709
188246
  async function prepareProductionContext(root, projectId, client) {
@@ -187713,8 +188250,8 @@ async function prepareProductionContext(root, projectId, client) {
187713
188250
  const remote = async () => {
187714
188251
  const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
187715
188252
  const snapshot = result2.editorialSnapshot;
187716
- if (!snapshot || snapshot.projectId !== projectId || typeof snapshot.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.contextVersion) || !snapshot.sourceHashes || typeof snapshot.sourceHashes !== "object" || Array.isArray(snapshot.sourceHashes) || Object.values(snapshot.sourceHashes).some((hash8) => typeof hash8 !== "string" || !/^[a-f0-9]{64}$/.test(hash8))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service did not return a versioned editorial context.", "Update the service before connected verification, or explicitly use --offline to check local documents only.");
187717
- if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash8) => typeof hash8 !== "string" || !/^[a-f0-9]{64}$/.test(hash8)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
188253
+ if (!snapshot || snapshot.projectId !== projectId || typeof snapshot.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.contextVersion) || !snapshot.sourceHashes || typeof snapshot.sourceHashes !== "object" || Array.isArray(snapshot.sourceHashes) || Object.values(snapshot.sourceHashes).some((hash9) => typeof hash9 !== "string" || !/^[a-f0-9]{64}$/.test(hash9))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service did not return a versioned editorial context.", "Update the service before connected verification, or explicitly use --offline to check local documents only.");
188254
+ if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash9) => typeof hash9 !== "string" || !/^[a-f0-9]{64}$/.test(hash9)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
187718
188255
  const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
187719
188256
  if (stableJson(portableHashes) !== (snapshot.effectiveSourceHashes ? sourceKey : stableJson(resolved.lock.sourceHashes))) throw new CliError("PRODUCTION_CONTEXT_CONFLICT", "Local and web project preferences or material differ.", "Use status and pull --project to inspect/reconcile changes. Do not overwrite either side automatically.");
187720
188257
  return snapshot.contextVersion;
@@ -187743,14 +188280,14 @@ var localPath = (id3) => {
187743
188280
  };
187744
188281
  async function indexSfx(directory, input, bankId) {
187745
188282
  const root = await ensureRoot(directory), target = localPath(bankId), folder = await assertNoMediaSymlinks(input);
187746
- if (!(await lstat12(folder)).isDirectory()) throw new Error("SFX input must be a directory.");
188283
+ if (!(await lstat13(folder)).isDirectory()) throw new Error("SFX input must be a directory.");
187747
188284
  const entries = [], paths2 = {}, failures = [];
187748
- const files = await readdir7(folder, { withFileTypes: true });
188285
+ const files = await readdir10(folder, { withFileTypes: true });
187749
188286
  const selected = files.filter((e) => e.isFile() && [".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aif", ".aiff"].includes(extname3(e.name).toLowerCase()));
187750
188287
  if (selected.length > 100) throw new Error("Choose a folder with up to 100 audio files; split larger banks by purpose. No files were changed.");
187751
188288
  for (const file of selected.sort((a, b) => a.name.localeCompare(b.name))) {
187752
188289
  try {
187753
- const probe2 = await probeLocalMedia(join9(folder, file.name));
188290
+ const probe2 = await probeLocalMedia(join10(folder, file.name));
187754
188291
  if (!probe2.durationSeconds || probe2.durationSeconds > 600 || !probe2.streams.some((s) => s.type === "audio") || probe2.streams.some((s) => s.type === "video" && !s.attachedPicture)) throw new Error("Expected a measured audio effect up to 600 seconds.");
187755
188292
  const id3 = "sfx-" + probe2.sha256.slice(0, 24);
187756
188293
  if (paths2[id3]) continue;
@@ -187813,8 +188350,8 @@ async function remoteSfx(client, subcommand, params) {
187813
188350
  }
187814
188351
 
187815
188352
  // packages/cli/src/media-preview.ts
187816
- import { chmod, link as link3, mkdtemp, rm as rm2 } from "node:fs/promises";
187817
- import { dirname as dirname11, join as join10 } from "node:path";
188353
+ import { chmod as chmod2, link as link3, mkdtemp, rm as rm2 } from "node:fs/promises";
188354
+ import { dirname as dirname12, join as join11 } from "node:path";
187818
188355
  async function prepareMediaPreview(root, file, out, quality = 720, audioStream) {
187819
188356
  if (![720, 1080].includes(quality) || !out.endsWith(".mp4")) throw new CliError("INVALID_ARGUMENT", "Use --quality 720 or 1080 and a new .mp4 output.", "Previews belong under .editorbrain-local/.");
187820
188357
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
@@ -187827,14 +188364,14 @@ async function prepareMediaPreview(root, file, out, quality = 720, audioStream)
187827
188364
  if (/^(yuva|gbrap|rgba|bgra|argb|abgr|ya)/.test(videos[0].pixelFormat ?? "")) throw new CliError("PREVIEW_ALPHA", "Transparent media needs an explicit background for review.", "Keep the alpha master and export a composited review copy first.");
187828
188365
  const selected = audioStream === void 0 ? audio[0] : audio.find((s) => s.index === audioStream);
187829
188366
  if (audioStream !== void 0 && !selected) throw new CliError("INVALID_ARGUMENT", "The selected audio stream does not exist.", "Inspect the material before selecting a track.");
187830
- const target = await prepareSampleDirectory(root, out), temp = await mkdtemp(join10(dirname11(target), ".preview-"));
188367
+ const target = await prepareSampleDirectory(root, out), temp = await mkdtemp(join11(dirname12(target), ".preview-"));
187831
188368
  try {
187832
- const prepared = join10(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
188369
+ const prepared = join11(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
187833
188370
  await runMediaTool("ffmpeg", ["-v", "error", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-map", `0:${videos[0].index}`, ...selected ? ["-map", `0:${selected.index}`, "-c:a", "aac", "-b:a", "128k"] : ["-an"], "-sn", "-dn", "-map_metadata", "-1", "-vf", `scale=w='min(iw,${edge})':h='min(ih,${edge})':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1`, "-c:v", "libx264", "-preset", "fast", "-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart", prepared], { timeoutMs: 6e5 });
187834
188371
  const result2 = await probeLocalMedia(prepared);
187835
188372
  if (result2.durationSeconds === null || Math.abs(result2.durationSeconds - source2.durationSeconds) > 0.25 || result2.streams.some((s) => s.type === "audio") !== !!selected) throw new CliError("PREVIEW_VERIFICATION", "Preview duration or audio does not match the source.", "No output was accepted. Inspect source timing in your editor.");
187836
188373
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during compression.", "Retry with a stable original.");
187837
- await chmod(prepared, 384);
188374
+ await chmod2(prepared, 384);
187838
188375
  await link3(prepared, target);
187839
188376
  return { kind: "editorbrain.review-preview", path: target, sha256: result2.sha256, sourceSha256: source2.sha256, sourceBytes: source2.bytes, bytes: result2.bytes, durationSeconds: result2.durationSeconds, quality, originalPreserved: true, uploaded: false, uploadEligible: result2.bytes <= 90 * 1024 * 1024, savedPercent: Math.round((1 - result2.bytes / source2.bytes) * 100), purpose: "preview", note: "Review copy, not an export master. Inspect text, color and audio before sharing. Small sources may become larger; originals remain untouched." };
187840
188377
  } finally {
@@ -187844,8 +188381,8 @@ async function prepareMediaPreview(root, file, out, quality = 720, audioStream)
187844
188381
 
187845
188382
  // packages/cli/src/studio-audio.ts
187846
188383
  import { link as link4, mkdtemp as mkdtemp2, readFile as readFile6, rm as rm3 } from "node:fs/promises";
187847
- import { dirname as dirname12, join as join11 } from "node:path";
187848
- import { createHash as createHash10 } from "node:crypto";
188384
+ import { dirname as dirname13, join as join12 } from "node:path";
188385
+ import { createHash as createHash12 } from "node:crypto";
187849
188386
  async function prepareStudioAudio(root, file, out, streamIndex) {
187850
188387
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
187851
188388
  const audio = source2.streams.filter((stream) => stream.type === "audio");
@@ -187855,16 +188392,16 @@ async function prepareStudioAudio(root, file, out, streamIndex) {
187855
188392
  if (!selected) throw new CliError("INVALID_ARGUMENT", "The selected stream is not an audio track.", "Inspect media inventory before selecting a track.");
187856
188393
  if (source2.durationSeconds === null || source2.durationSeconds > 1800) throw new CliError("AUDIO_DURATION_LIMIT", "Tempo preparation requires a known source duration up to 30 minutes.", "Split long recordings explicitly and preserve each segment offset; never silently truncate.");
187857
188394
  if (!out.endsWith(".wav")) throw new CliError("INVALID_ARGUMENT", "The prepared output must be a .wav file.", "Use --out .editorbrain-local/studio/source.wav.");
187858
- const target = await prepareSampleDirectory(root, out), temp = await mkdtemp2(join11(dirname12(target), ".tempo-"));
188395
+ const target = await prepareSampleDirectory(root, out), temp = await mkdtemp2(join12(dirname13(target), ".tempo-"));
187859
188396
  try {
187860
- const prepared = join11(temp, "audio.wav");
188397
+ const prepared = join12(temp, "audio.wav");
187861
188398
  await runMediaTool("ffmpeg", ["-v", "error", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-map", `0:${selected.index}`, "-vn", "-sn", "-dn", "-map_metadata", "-1", "-af", "aresample=16000:async=1:first_pts=0", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-t", "1801", prepared], { timeoutMs: 6e5 });
187862
188399
  const verified = await probeLocalMedia(prepared);
187863
188400
  if (verified.durationSeconds === null || verified.durationSeconds > 1800 || verified.bytes > 90 * 1024 * 1024) throw new CliError("AUDIO_DURATION_LIMIT", "The decoded audio exceeds the supported duration.", "Inspect source timestamps; no file was uploaded.");
187864
188401
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during extraction.", "Retry only after the source is stable.");
187865
- const bytes = await readFile6(prepared), hash8 = createHash10("sha256").update(bytes).digest("hex");
188402
+ const bytes = await readFile6(prepared), hash9 = createHash12("sha256").update(bytes).digest("hex");
187866
188403
  await link4(prepared, target);
187867
- return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash8, bytes: bytes.length, durationMs: Math.round(verified.durationSeconds * 1e3), mimeType: "audio/wav", sourceSha256: source2.sha256, sourcePath: source2.path, audioStream: selected.index, sourceStartTimeSeconds: source2.startTimeSeconds, timestampBasis: "milliseconds_from_container_start", silenceRemoved: false, uploaded: false, next: "Upload this WAV using assets upload, then quote Tempo with its assetId. Keep this source mapping locally; returned word times refer to this prepared audio." };
188404
+ return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash9, bytes: bytes.length, durationMs: Math.round(verified.durationSeconds * 1e3), mimeType: "audio/wav", sourceSha256: source2.sha256, sourcePath: source2.path, audioStream: selected.index, sourceStartTimeSeconds: source2.startTimeSeconds, timestampBasis: "milliseconds_from_container_start", silenceRemoved: false, uploaded: false, next: "Upload this WAV using assets upload, then quote Tempo with its assetId. Keep this source mapping locally; returned word times refer to this prepared audio." };
187868
188405
  } finally {
187869
188406
  await rm3(temp, { recursive: true, force: true });
187870
188407
  }
@@ -188061,9 +188598,9 @@ async function setup(options, runner = runHost) {
188061
188598
 
188062
188599
  // packages/cli/src/onboarding.ts
188063
188600
  import { createServer } from "node:http";
188064
- import { randomBytes, createHash as createHash11 } from "node:crypto";
188065
- import { join as join12, dirname as dirname13 } from "node:path";
188066
- import { mkdir as mkdir9 } from "node:fs/promises";
188601
+ import { randomBytes, createHash as createHash13 } from "node:crypto";
188602
+ import { join as join13, dirname as dirname14 } from "node:path";
188603
+ import { mkdir as mkdir10 } from "node:fs/promises";
188067
188604
 
188068
188605
  // packages/cli/src/onboarding-brand.ts
188069
188606
  var onboardingWordmark = '<svg xmlns="http://www.w3.org/2000/svg"\n width="873" height="131" viewBox="0 0 873.000000 131.000000"\n preserveAspectRatio="xMidYMid meet">\n<!-- Traced from approved Thought Loop lettering, excluding residual background. -->\n<g transform="translate(0.000000,131.000000) scale(0.100000,-0.100000)"\nfill="#f3ede3" stroke="none">\n<path d="M2116 1290 c-41 -13 -63 -36 -82 -87 -14 -36 -15 -50 -6 -81 31 -102\n157 -139 231 -68 50 48 58 116 23 183 -25 46 -107 72 -166 53z"/>\n<path d="M7491 1282 c-69 -34 -97 -113 -68 -185 30 -71 133 -101 204 -57 94\n57 80 202 -24 246 -43 19 -71 18 -112 -4z"/>\n<path d="M4771 1268 c-37 -13 -41 -39 -41 -314 0 -502 11 -894 27 -910 10 -10\n39 -14 97 -14 87 0 116 13 116 53 0 22 12 21 43 -3 75 -60 226 -86 338 -60\n129 30 250 123 302 233 31 66 57 171 57 230 -1 171 -105 339 -257 414 -67 33\n-85 38 -169 41 -113 5 -170 -7 -246 -53 -31 -19 -60 -35 -65 -35 -4 0 -6 84\n-5 188 5 230 5 229 -105 234 -40 2 -81 0 -92 -4z m552 -578 c59 -29 83 -51\n112 -105 32 -61 35 -157 6 -213 -25 -48 -77 -97 -123 -116 -51 -22 -153 -20\n-203 3 -145 66 -185 260 -77 375 67 72 198 97 285 56z"/>\n<path d="M1699 1243 c-11 -13 -13 -56 -11 -205 2 -114 0 -188 -6 -188 -5 0\n-35 15 -67 34 -87 53 -175 67 -285 46 -210 -40 -360 -232 -360 -461 0 -256\n193 -459 436 -459 77 0 155 25 227 74 l52 34 6 -29 c11 -52 24 -59 113 -59 44\n0 86 4 92 8 33 22 36 52 29 330 -3 152 -7 412 -10 576 -3 233 -7 301 -17 307\n-7 5 -52 9 -99 9 -69 0 -89 -3 -100 -17z m-133 -569 c137 -84 153 -274 33\n-377 -121 -104 -299 -65 -377 83 -21 38 -17 151 6 197 65 124 221 170 338 97z"/>\n<path d="M2543 1168 c-4 -7 -10 -65 -13 -128 l-5 -115 -60 -3 c-32 -2 -65 -8\n-72 -14 -9 -7 -13 -38 -13 -94 0 -103 8 -114 90 -114 l58 0 4 -232 c3 -261 9\n-284 82 -366 101 -111 320 -117 422 -11 l29 30 -35 65 c-47 89 -62 99 -111 73\n-49 -24 -80 -24 -112 1 -39 31 -47 77 -47 267 l0 171 98 4 c128 4 132 7 132\n110 0 106 -3 108 -129 108 l-101 0 0 114 c0 146 0 146 -120 146 -60 0 -91 -4\n-97 -12z"/>\n<path d="M4515 941 c-49 -12 -108 -47 -144 -85 -43 -44 -51 -45 -51 -5 0 62\n-11 69 -108 69 -55 0 -95 -5 -105 -12 -16 -12 -17 -46 -15 -431 3 -489 -8\n-447 123 -447 118 0 113 -12 117 260 3 189 6 231 21 265 39 87 122 144 212\n145 75 0 78 5 83 113 5 119 -3 137 -61 136 -23 -1 -55 -4 -72 -8z"/>\n<path d="M6218 940 c-47 -14 -135 -69 -152 -95 -23 -36 -36 -31 -36 13 0 21\n-5 43 -12 50 -16 16 -180 16 -196 0 -9 -9 -12 -119 -12 -435 0 -489 -12 -443\n118 -443 116 0 112 -8 112 241 0 238 9 286 68 351 48 53 102 78 173 78 30 0\n60 5 67 12 8 8 12 48 12 113 0 65 -4 105 -12 113 -13 13 -89 15 -130 2z"/>\n<path d="M8259 940 c-54 -9 -133 -48 -172 -84 -33 -30 -47 -26 -47 13 0 15 -5\n32 -12 39 -14 14 -166 16 -188 2 -13 -8 -15 -67 -15 -428 0 -337 3 -423 14\n-436 10 -12 32 -16 97 -16 129 0 124 -11 124 273 0 129 5 249 10 269 43 154\n261 187 343 53 l27 -46 0 -253 c0 -309 -5 -296 125 -296 135 0 127 -21 123\n343 -3 290 -4 304 -26 352 -34 74 -68 118 -115 152 -75 54 -192 80 -288 63z"/>\n<path d="M350 926 c-102 -29 -192 -95 -249 -184 -97 -153 -97 -381 0 -534 89\n-139 233 -206 422 -195 76 4 99 10 163 41 72 36 174 124 174 151 0 16 -47 57\n-107 91 l-45 27 -26 -22 c-90 -72 -101 -76 -193 -76 -81 0 -90 2 -131 30 -43\n31 -88 95 -88 128 0 16 22 17 314 17 314 0 315 0 330 22 41 58 -8 274 -79 350\n-14 15 -25 30 -25 34 0 20 -128 100 -190 118 -64 19 -205 20 -270 2z m239\n-215 c44 -23 86 -72 96 -113 l7 -28 -211 0 c-171 0 -211 3 -211 14 0 17 45 84\n73 107 58 50 170 58 246 20z"/>\n<path d="M3401 924 c-244 -65 -390 -320 -326 -567 88 -338 502 -461 774 -230\n98 84 151 205 151 348 0 50 -7 111 -15 138 -46 153 -170 271 -328 313 -66 18\n-187 17 -256 -2z m239 -242 c62 -32 115 -100 125 -163 33 -194 -166 -341 -343\n-253 -51 26 -79 55 -115 123 -22 43 -16 134 13 190 60 117 205 164 320 103z"/>\n<path d="M6723 930 c-47 -10 -146 -55 -175 -79 -11 -9 -28 -23 -37 -31 -10 -8\n-38 -45 -63 -81 -61 -90 -82 -168 -76 -296 3 -88 7 -106 41 -176 77 -164 225\n-257 407 -257 64 0 167 33 218 70 51 37 62 37 62 4 0 -42 25 -53 117 -54 73 0\n83 2 97 22 14 19 16 76 16 418 0 298 -3 401 -13 420 -12 23 -18 25 -101 28\n-95 3 -116 -5 -116 -43 0 -35 -11 -37 -48 -9 -75 58 -223 87 -329 64z m243\n-256 c73 -45 107 -100 112 -180 6 -85 -16 -141 -73 -192 -109 -95 -276 -79\n-358 36 -27 37 -32 54 -35 116 -3 48 1 84 10 106 57 136 221 190 344 114z"/>\n<path d="M2065 896 c-14 -20 -15 -76 -13 -431 3 -476 -8 -435 125 -435 123 0\n115 -32 112 447 -1 331 -4 402 -17 420 -13 21 -22 23 -103 23 -82 0 -90 -2\n-104 -24z"/>\n<path d="M7459 903 c-11 -13 -14 -94 -14 -430 0 -483 -10 -443 115 -443 119 0\n110 -35 110 447 0 482 10 443 -117 443 -63 0 -84 -4 -94 -17z"/>\n</g>\n</svg>\n';
@@ -188875,7 +189412,7 @@ async function syncOnboardingDocuments(client, root, files, options) {
188875
189412
  // packages/cli/src/onboarding.ts
188876
189413
  var failure = (code, message, hint = "Reopen onboarding against the current files. Nothing is overwritten silently.") => new CliError(code, message, hint);
188877
189414
  function starterOutputId(brandId2) {
188878
- return `onboarding-${brandId2.slice(0, 48)}-${createHash11("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
189415
+ return `onboarding-${brandId2.slice(0, 48)}-${createHash13("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
188879
189416
  }
188880
189417
  function scaffold(brandId2, projectId) {
188881
189418
  const files = Object.fromEntries(Object.entries(createWorkspace({ brand: brandId2, project: projectId })).filter(([p]) => !p.startsWith(`.editorbrain/brands/${brandId2}/`)));
@@ -188931,14 +189468,14 @@ async function createOnboarding(options) {
188931
189468
  const directory = options.out ?? `.editorbrain-local/onboarding/${brandId2}-${Date.now()}-${randomBytes(3).toString("hex")}`;
188932
189469
  await productionOutputPath(root, `${directory}/session.json`);
188933
189470
  const target = await checkedPath(root, directory, false);
188934
- await mkdir9(dirname13(target), { recursive: true });
188935
- await mkdir9(target);
189471
+ await mkdir10(dirname14(target), { recursive: true });
189472
+ await mkdir10(target);
188936
189473
  const saved = await snapshots(root, brandId2, projectId), files = Object.fromEntries(Object.entries(saved).flatMap(([p, s]) => s ? [[p, s.content]] : []));
188937
189474
  const intake = onboardingIntakeFromFiles(brandId2, files);
188938
189475
  const session = { schemaVersion: 1, kind: "editorbrain.onboarding", brandId: brandId2, projectId, intake, snapshots: saved };
188939
189476
  await atomicWrite(root, `${directory}/session.json`, stableJson(session), { document: false, overwrite: false, mode: 384 });
188940
189477
  await atomicWrite(root, `${directory}/index.html`, renderOnboardingArtifact({ intake, requiresIdentity: saved[`.editorbrain/brands/${brandId2}/brand.md`] === null }), { document: false, overwrite: false, mode: 384 });
188941
- return { schemaVersion: 1, brandId: brandId2, projectId, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0), artifact: join12(root, directory, "index.html"), session: `${directory}/session.json`, answers: `${directory}/answers.json`, savedToBrain: false, next: "Show the HTML artifact, or run onboarding serve --session <session>. Static artifacts download answers: put them in this workspace and run onboarding apply --session <session> --file <answers>. Never fill choices on the user\u2019s behalf." };
189478
+ return { schemaVersion: 1, brandId: brandId2, projectId, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0), artifact: join13(root, directory, "index.html"), session: `${directory}/session.json`, answers: `${directory}/answers.json`, savedToBrain: false, next: "Show the HTML artifact, or run onboarding serve --session <session>. Static artifacts download answers: put them in this workspace and run onboarding apply --session <session> --file <answers>. Never fill choices on the user\u2019s behalf." };
188942
189479
  }
188943
189480
  async function applyOnboarding(options) {
188944
189481
  const root = await ensureRoot(options.directory);
@@ -188969,7 +189506,7 @@ async function applyOnboarding(options) {
188969
189506
  if (now !== current2[item.path]?.content) throw failure("ONBOARDING_CONFLICT", `Document changed while applying: ${item.path}`);
188970
189507
  await atomicWrite(root, item.path, item.content, { overwrite: now !== void 0 });
188971
189508
  }
188972
- await atomicWrite(root, `${dirname13(options.session)}/applied.json`, stableJson({ schemaVersion: 1, brandId: session.brandId, projectId: session.projectId, appliedAt: (/* @__PURE__ */ new Date()).toISOString(), accountSetup: intake.accountSetup, paths: Object.keys(merged) }), { document: false, mode: 384 });
189509
+ await atomicWrite(root, `${dirname14(options.session)}/applied.json`, stableJson({ schemaVersion: 1, brandId: session.brandId, projectId: session.projectId, appliedAt: (/* @__PURE__ */ new Date()).toISOString(), accountSetup: intake.accountSetup, paths: Object.keys(merged) }), { document: false, mode: 384 });
188973
189510
  }
188974
189511
  return { schemaVersion: 1, brandId: session.brandId, projectId: session.projectId, dryRun: !!options.dryRun, changed: pending.map((w) => w.path), documents: Object.keys(merged).length, brainGenerated: !options.dryRun, accountActions: plan.accountActions, aiAnalyzed: false, cloudSynced: false, next: "Local documents are ready after apply. Install the skill if needed, authenticate, use onboarding sync for this session, then complete and verify requested accountActions. Only if requested, use brain prepare and review before brain accept. A brain is editorial context, not a rendered video." };
188975
189512
  }, { migrateLegacy: !options.dryRun });
@@ -188978,7 +189515,7 @@ async function syncOnboarding(client, options) {
188978
189515
  const root = await ensureRoot(options.directory);
188979
189516
  return withWorkspaceLock(root, async () => {
188980
189517
  const session = await readSession(root, options.session);
188981
- const receipt = await readProductionJson(root, `${dirname13(options.session)}/applied.json`);
189518
+ const receipt = await readProductionJson(root, `${dirname14(options.session)}/applied.json`);
188982
189519
  if (receipt.brandId !== session.brandId || receipt.projectId !== session.projectId) throw failure("ONBOARDING_NOT_APPLIED", "Apply the reviewed choices locally before syncing.");
188983
189520
  const files = {};
188984
189521
  for (const path of paths(session.brandId, session.projectId)) {
@@ -188995,7 +189532,7 @@ async function syncOnboarding(client, options) {
188995
189532
  async function serveOnboarding(options) {
188996
189533
  const root = await ensureRoot(options.directory), session = await readSession(root, options.session), seconds = options.timeoutSeconds ?? 1800;
188997
189534
  if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) throw failure("INVALID_ARGUMENT", "Timeout must be between 1 and 3600 seconds.");
188998
- const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname13(options.session)}/answers.json`;
189535
+ const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname14(options.session)}/answers.json`;
188999
189536
  let origin = "", consumed = false, busy = false, server;
189000
189537
  let complete, reject;
189001
189538
  const done = new Promise((yes, no) => {
@@ -189035,7 +189572,7 @@ async function serveOnboarding(options) {
189035
189572
  await atomicWrite(root, answers, stableJson(intake), { document: false, overwrite: false, mode: 384 });
189036
189573
  consumed = true;
189037
189574
  send(200, { saved: true, path: answers });
189038
- complete({ schemaVersion: 1, saved: true, answers: join12(root, answers), session: options.session, applied: false, next: "Review saved choices and run onboarding apply with this session and answers file." });
189575
+ complete({ schemaVersion: 1, saved: true, answers: join13(root, answers), session: options.session, applied: false, next: "Review saved choices and run onboarding apply with this session and answers file." });
189039
189576
  } catch (e) {
189040
189577
  busy = false;
189041
189578
  send(400, { error: e.message.slice(0, 300) });
@@ -189055,7 +189592,7 @@ async function serveOnboarding(options) {
189055
189592
  process.once("SIGINT", stop);
189056
189593
  process.once("SIGTERM", stop);
189057
189594
  try {
189058
- options.onReady?.({ url: `${origin}${prefix}/`, answers: join12(root, answers) });
189595
+ options.onReady?.({ url: `${origin}${prefix}/`, answers: join13(root, answers) });
189059
189596
  return await done;
189060
189597
  } finally {
189061
189598
  clearTimeout(timer);
@@ -189078,7 +189615,7 @@ async function onboardingStatus(options) {
189078
189615
  var object9 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
189079
189616
  var integer = (value, min = 0) => Number.isSafeInteger(value) && Number(value) >= min;
189080
189617
  var text9 = (value, max) => typeof value === "string" && !!value.trim() && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
189081
- var hash5 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
189618
+ var hash6 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
189082
189619
  var date = (value) => text9(value, 64) && Number.isFinite(Date.parse(value));
189083
189620
  function invalidInput(message) {
189084
189621
  return new CliError("INVALID_ARGUMENT", message, "Use brain status --brand ID; read the current design.md revision before preparing. Acceptance requires the reviewed run and its source revision.");
@@ -189095,7 +189632,7 @@ function validateInput(input, accept = false) {
189095
189632
  if (!object9(input) || Object.keys(input).some((key) => !(accept ? ["brandId", "expectedDesignRevision", "runId", "reviewed"] : ["brandId", "expectedDesignRevision"]).includes(key))) throw invalidInput("Only the brand, document revision and explicit reviewed run are accepted.");
189096
189633
  brandId(input.brandId);
189097
189634
  if (!integer(input.expectedDesignRevision, 1)) throw invalidInput("A positive source design revision is required.");
189098
- if (accept && (!hash5(input.runId) || input.reviewed !== true)) throw invalidInput("Accept only a specific proposal already reviewed and approved by the user; --run and --reviewed are required.");
189635
+ if (accept && (!hash6(input.runId) || input.reviewed !== true)) throw invalidInput("Accept only a specific proposal already reviewed and approved by the user; --run and --reviewed are required.");
189099
189636
  }
189100
189637
  function invalidResponse(write) {
189101
189638
  return new CliError(
@@ -189110,11 +189647,11 @@ function brainState(value, brand, write = false) {
189110
189647
  const invalid7 = () => {
189111
189648
  throw invalidResponse(write);
189112
189649
  };
189113
- if (!object9(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text9(value.notice, 2e3) || value.contextVersion !== void 0 && !hash5(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid7();
189650
+ if (!object9(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text9(value.notice, 2e3) || value.contextVersion !== void 0 && !hash6(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid7();
189114
189651
  let run = null;
189115
189652
  if (value.run !== null) {
189116
189653
  const row = value.run;
189117
- if (!object9(row) || !hash5(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date(row.createdAt) || !date(row.updatedAt)) return invalid7();
189654
+ if (!object9(row) || !hash6(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date(row.createdAt) || !date(row.updatedAt)) return invalid7();
189118
189655
  if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid7();
189119
189656
  let proposal = null;
189120
189657
  if (row.proposal !== null) {
@@ -189350,10 +189887,10 @@ async function loginWithDevice(options, overrides = {}) {
189350
189887
  }
189351
189888
 
189352
189889
  // packages/cli/src/index.ts
189353
- import { chmod as chmod2, lstat as lstat16, mkdir as mkdir14, open as open13 } from "node:fs/promises";
189354
- import { constants as constants12 } from "node:fs";
189890
+ import { chmod as chmod3, lstat as lstat17, mkdir as mkdir15, open as open14 } from "node:fs/promises";
189891
+ import { constants as constants13 } from "node:fs";
189355
189892
  import { homedir as homedir3 } from "node:os";
189356
- import { basename as basename6, dirname as dirname18, extname as extname7, join as join15, resolve as resolve12 } from "node:path";
189893
+ import { basename as basename6, dirname as dirname19, extname as extname7, join as join16, resolve as resolve12 } from "node:path";
189357
189894
 
189358
189895
  // packages/cli/src/direction-context.ts
189359
189896
  async function prepareDirectionContext(root, client, projectId) {
@@ -189527,8 +190064,8 @@ var record12 = (value) => value !== null && typeof value === "object" && !Array.
189527
190064
  var array2 = (value) => Array.isArray(value) ? value : [];
189528
190065
  function plain(value, max = 2e3) {
189529
190066
  if (typeof value !== "string" || value.length > 16e3) return null;
189530
- const text12 = value.replace(/<[^>]*>/g, " ").replace(/&#(x[0-9a-f]+|[0-9]+);/gi, (_, number2) => {
189531
- const code = number2[0].toLowerCase() === "x" ? parseInt(number2.slice(1), 16) : Number(number2);
190067
+ const text12 = value.replace(/<[^>]*>/g, " ").replace(/&#(x[0-9a-f]+|[0-9]+);/gi, (_, number3) => {
190068
+ const code = number3[0].toLowerCase() === "x" ? parseInt(number3.slice(1), 16) : Number(number3);
189532
190069
  return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
189533
190070
  }).replace(/&(amp|quot|apos|lt|gt|nbsp);/g, (_, entity) => ({ amp: "&", quot: '"', apos: "'", lt: "<", gt: ">", nbsp: " " })[entity]).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, " ").replace(/\s+/g, " ").trim();
189534
190071
  return text12 ? text12.slice(0, max) : null;
@@ -189850,9 +190387,9 @@ async function searchMediaSources(options, dependencies = {}) {
189850
190387
  }
189851
190388
 
189852
190389
  // packages/cli/src/media-inventory.ts
189853
- import { createHash as createHash12 } from "node:crypto";
189854
- import { link as link5, lstat as lstat13, mkdir as mkdir10, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm4 } from "node:fs/promises";
189855
- import { basename as basename3, dirname as dirname14, extname as extname4, join as join13 } from "node:path";
190390
+ import { createHash as createHash14 } from "node:crypto";
190391
+ import { link as link5, lstat as lstat14, mkdir as mkdir11, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm4 } from "node:fs/promises";
190392
+ import { basename as basename3, dirname as dirname15, extname as extname4, join as join14 } from "node:path";
189856
190393
  var GENERATED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "output", "outputs", "renders", "render", "cache", "caches", "proxies", "proxy", "samples", "thumbnails", "coverage", "venv", "__pycache__"]);
189857
190394
  function mediaFailure(error) {
189858
190395
  if (error instanceof MediaToolError) return { code: error.code, message: error.message };
@@ -189878,7 +190415,7 @@ async function inventoryMedia(options) {
189878
190415
  }
189879
190416
  report.scannedEntries++;
189880
190417
  try {
189881
- const stat = await lstat13(path);
190418
+ const stat = await lstat14(path);
189882
190419
  if (stat.isSymbolicLink()) {
189883
190420
  if (explicit) throw new MediaToolError("MEDIA_SYMLINK", "Symlink inputs are not followed. Use the original local path.");
189884
190421
  skip(path, "symlink_not_followed");
@@ -189904,7 +190441,7 @@ async function inventoryMedia(options) {
189904
190441
  skip(path, "remaining_entries_not_scanned", true);
189905
190442
  break;
189906
190443
  }
189907
- await visit(join13(path, entry.name), depth + 1);
190444
+ await visit(join14(path, entry.name), depth + 1);
189908
190445
  }
189909
190446
  } else if (!stat.isFile()) {
189910
190447
  if (explicit) throw new MediaToolError("MEDIA_NOT_REGULAR", "The explicit media input must be a regular local file or directory.");
@@ -189939,23 +190476,23 @@ async function sampleMedia(options) {
189939
190476
  if (!source2.streams.some((stream) => stream.type === "video")) throw new MediaToolError("MEDIA_VIDEO_REQUIRED", "Frame sampling requires a video or image stream.");
189940
190477
  if (source2.durationSeconds !== null && options.times.some((time) => time >= source2.durationSeconds)) throw new MediaToolError("MEDIA_SAMPLE_OUT_OF_RANGE", "A requested sample is outside the known media duration.");
189941
190478
  const outputDirectory = resolveLocalMediaPath(options.outputDirectory);
189942
- await assertNoMediaSymlinks(dirname14(outputDirectory));
190479
+ await assertNoMediaSymlinks(dirname15(outputDirectory));
189943
190480
  try {
189944
- await mkdir10(outputDirectory);
190481
+ await mkdir11(outputDirectory);
189945
190482
  } catch (error) {
189946
190483
  if (error.code !== "EEXIST") throw error;
189947
190484
  }
189948
190485
  await assertNoMediaSymlinks(outputDirectory);
189949
- if (!(await lstat13(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
189950
- const temp = await mkdtemp3(join13(outputDirectory, ".editorbrain-samples-"));
189951
- const tempStat = await lstat13(temp);
190486
+ if (!(await lstat14(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
190487
+ const temp = await mkdtemp3(join14(outputDirectory, ".editorbrain-samples-"));
190488
+ const tempStat = await lstat14(temp);
189952
190489
  const frames = [];
189953
190490
  const created = [];
189954
190491
  try {
189955
190492
  for (let index = 0; index < options.times.length; index++) {
189956
190493
  const time = options.times[index];
189957
190494
  const filename = `${source2.sha256.slice(0, 12)}-${String(index + 1).padStart(2, "0")}-${Math.round(time * 1e3)}ms.jpg`;
189958
- const temporary = join13(temp, filename), output2 = join13(outputDirectory, filename);
190495
+ const temporary = join14(temp, filename), output2 = join14(outputDirectory, filename);
189959
190496
  await runMediaTool("ffmpeg", ["-v", "error", "-n", "-ss", String(time), ...localInputArgs(file), "-map", "0:v:0", "-frames:v", "1", "-an", "-sn", "-dn", "-vf", "scale=960:960:force_original_aspect_ratio=decrease", "-q:v", "3", "-update", "1", temporary], { timeoutMs: 6e4 });
189960
190497
  const bytes = await readFile7(temporary);
189961
190498
  if (!bytes.length) throw new MediaToolError("MEDIA_SAMPLE_EMPTY", "The requested frame did not produce a usable image.");
@@ -189965,9 +190502,9 @@ async function sampleMedia(options) {
189965
190502
  if (error.code === "EEXIST") throw new MediaToolError("MEDIA_OUTPUT_EXISTS", "A sample output already exists. Choose a new output directory; existing files are never overwritten.");
189966
190503
  throw error;
189967
190504
  }
189968
- const outputStat = await lstat13(output2);
190505
+ const outputStat = await lstat14(output2);
189969
190506
  created.push({ path: output2, ino: outputStat.ino, dev: outputStat.dev, size: outputStat.size, mtimeMs: outputStat.mtimeMs, ctimeMs: outputStat.ctimeMs });
189970
- frames.push({ path: output2, sha256: createHash12("sha256").update(bytes).digest("hex"), bytes: bytes.length, requestedTimeSeconds: time, actualPresentationTimeSeconds: null });
190507
+ frames.push({ path: output2, sha256: createHash14("sha256").update(bytes).digest("hex"), bytes: bytes.length, requestedTimeSeconds: time, actualPresentationTimeSeconds: null });
189971
190508
  }
189972
190509
  const after = await probeLocalMedia(file);
189973
190510
  if (source2.sha256 !== after.sha256) throw new MediaToolError("MEDIA_FILE_CHANGED", "The source changed while frames were being sampled. Retry with a stable source.");
@@ -189976,7 +190513,7 @@ async function sampleMedia(options) {
189976
190513
  for (const file2 of created) {
189977
190514
  try {
189978
190515
  await assertNoMediaSymlinks(file2.path);
189979
- const current2 = await lstat13(file2.path);
190516
+ const current2 = await lstat14(file2.path);
189980
190517
  if (current2.ino === file2.ino && current2.dev === file2.dev && current2.size === file2.size && current2.mtimeMs === file2.mtimeMs && current2.ctimeMs === file2.ctimeMs) await rm4(file2.path, { force: true });
189981
190518
  } catch {
189982
190519
  }
@@ -189985,7 +190522,7 @@ async function sampleMedia(options) {
189985
190522
  } finally {
189986
190523
  try {
189987
190524
  await assertNoMediaSymlinks(temp);
189988
- const current2 = await lstat13(temp);
190525
+ const current2 = await lstat14(temp);
189989
190526
  if (current2.ino === tempStat.ino && current2.dev === tempStat.dev) await rm4(temp, { recursive: true, force: true });
189990
190527
  } catch {
189991
190528
  }
@@ -190012,7 +190549,7 @@ function validateRenderCheckProfile(value) {
190012
190549
  const black = root.black === void 0 ? {} : object11(root.black, "black", ["enabled", "minDurationSeconds", "pixelThreshold", "pictureBlackRatio"]);
190013
190550
  const peak = root.peak === void 0 ? {} : object11(root.peak, "peak", ["enabled", "thresholdDbFS"]);
190014
190551
  const limits = root.limits === void 0 ? {} : object11(root.limits, "limits", ["timeoutMs", "maxOutputBytes"]);
190015
- const number2 = (v, name, min, max, fallback, integer2 = false) => {
190552
+ const number3 = (v, name, min, max, fallback, integer2 = false) => {
190016
190553
  if (v === void 0 && fallback !== void 0) return fallback;
190017
190554
  if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer2 && !Number.isInteger(v)) invalidProfile(`${name} must be ${integer2 ? "an integer" : "a finite number"} between ${min} and ${max}.`);
190018
190555
  return v;
@@ -190024,18 +190561,18 @@ function validateRenderCheckProfile(value) {
190024
190561
  };
190025
190562
  if (root.audio !== void 0 && !["required", "optional", "forbidden"].includes(root.audio)) invalidProfile("audio must be required, optional or forbidden.");
190026
190563
  const validatedExpected = {};
190027
- for (const key of ["width", "height"]) if (expected[key] !== void 0) validatedExpected[key] = number2(expected[key], `expected.${key}`, 1, 32768, void 0, true);
190028
- if (expected.fps !== void 0) validatedExpected.fps = number2(expected.fps, "expected.fps", 1e-6, 1e3);
190029
- if (expected.durationSeconds !== void 0) validatedExpected.durationSeconds = number2(expected.durationSeconds, "expected.durationSeconds", 1e-6, 864e4);
190564
+ for (const key of ["width", "height"]) if (expected[key] !== void 0) validatedExpected[key] = number3(expected[key], `expected.${key}`, 1, 32768, void 0, true);
190565
+ if (expected.fps !== void 0) validatedExpected.fps = number3(expected.fps, "expected.fps", 1e-6, 1e3);
190566
+ if (expected.durationSeconds !== void 0) validatedExpected.durationSeconds = number3(expected.durationSeconds, "expected.durationSeconds", 1e-6, 864e4);
190030
190567
  return {
190031
190568
  schemaVersion: 1,
190032
190569
  expected: validatedExpected,
190033
- tolerance: { fps: number2(tolerance.fps, "tolerance.fps", 0, 1e3, 0.01), durationSeconds: number2(tolerance.durationSeconds, "tolerance.durationSeconds", 0, 86400, 0.1) },
190570
+ tolerance: { fps: number3(tolerance.fps, "tolerance.fps", 0, 1e3, 0.01), durationSeconds: number3(tolerance.durationSeconds, "tolerance.durationSeconds", 0, 86400, 0.1) },
190034
190571
  audio: root.audio ?? "optional",
190035
- silence: { enabled: enabled(silence.enabled, "silence.enabled"), minDurationSeconds: number2(silence.minDurationSeconds, "silence.minDurationSeconds", 1e-3, 86400, 0.75), thresholdDb: number2(silence.thresholdDb, "silence.thresholdDb", -150, 0, -50) },
190036
- black: { enabled: enabled(black.enabled, "black.enabled"), minDurationSeconds: number2(black.minDurationSeconds, "black.minDurationSeconds", 1e-3, 86400, 0.15), pixelThreshold: number2(black.pixelThreshold, "black.pixelThreshold", 0, 1, 0.1), pictureBlackRatio: number2(black.pictureBlackRatio, "black.pictureBlackRatio", 0, 1, 0.98) },
190037
- peak: { enabled: enabled(peak.enabled, "peak.enabled"), thresholdDbFS: number2(peak.thresholdDbFS, "peak.thresholdDbFS", -150, 0, -0.1) },
190038
- limits: { timeoutMs: number2(limits.timeoutMs, "limits.timeoutMs", 1, 6e5, 6e5, true), maxOutputBytes: number2(limits.maxOutputBytes, "limits.maxOutputBytes", 1024, 16777216, 4194304, true) }
190572
+ silence: { enabled: enabled(silence.enabled, "silence.enabled"), minDurationSeconds: number3(silence.minDurationSeconds, "silence.minDurationSeconds", 1e-3, 86400, 0.75), thresholdDb: number3(silence.thresholdDb, "silence.thresholdDb", -150, 0, -50) },
190573
+ black: { enabled: enabled(black.enabled, "black.enabled"), minDurationSeconds: number3(black.minDurationSeconds, "black.minDurationSeconds", 1e-3, 86400, 0.15), pixelThreshold: number3(black.pixelThreshold, "black.pixelThreshold", 0, 1, 0.1), pictureBlackRatio: number3(black.pictureBlackRatio, "black.pictureBlackRatio", 0, 1, 0.98) },
190574
+ peak: { enabled: enabled(peak.enabled, "peak.enabled"), thresholdDbFS: number3(peak.thresholdDbFS, "peak.thresholdDbFS", -150, 0, -0.1) },
190575
+ limits: { timeoutMs: number3(limits.timeoutMs, "limits.timeoutMs", 1, 6e5, 6e5, true), maxOutputBytes: number3(limits.maxOutputBytes, "limits.maxOutputBytes", 1024, 16777216, 4194304, true) }
190039
190576
  };
190040
190577
  }
190041
190578
  function errorCode(error) {
@@ -190257,10 +190794,10 @@ async function checkRender(options) {
190257
190794
  }
190258
190795
 
190259
190796
  // packages/cli/src/motion-components.ts
190260
- import { createHash as createHash13 } from "node:crypto";
190261
- import { constants as constants11 } from "node:fs";
190262
- import { lstat as lstat14, mkdir as mkdir11, open as open12, rmdir as rmdir2, unlink as unlink9 } from "node:fs/promises";
190263
- import { dirname as dirname15, extname as extname5, resolve as resolve9 } from "node:path";
190797
+ import { createHash as createHash15 } from "node:crypto";
190798
+ import { constants as constants12 } from "node:fs";
190799
+ import { lstat as lstat15, mkdir as mkdir12, open as open13, rmdir as rmdir2, unlink as unlink10 } from "node:fs/promises";
190800
+ import { dirname as dirname16, extname as extname5, resolve as resolve9 } from "node:path";
190264
190801
 
190265
190802
  // packages/core/src/motion-editorial.ts
190266
190803
  function createEditorialRenderer(config2, g) {
@@ -192094,7 +192631,7 @@ function inputPath(base, value) {
192094
192631
  }
192095
192632
  async function sourceFile(path, role, max) {
192096
192633
  await assertNoMediaSymlinks(path);
192097
- const handle = await open12(path, constants11.O_RDONLY | constants11.O_NOFOLLOW | constants11.O_NONBLOCK);
192634
+ const handle = await open13(path, constants12.O_RDONLY | constants12.O_NOFOLLOW | constants12.O_NONBLOCK);
192098
192635
  try {
192099
192636
  const before = await handle.stat();
192100
192637
  if (!before.isFile() || before.size === 0 || before.size > max) throw fail2(`${role} must be a nonempty regular file of at most ${max} bytes.`);
@@ -192107,9 +192644,9 @@ async function sourceFile(path, role, max) {
192107
192644
  }
192108
192645
  const after = await handle.stat();
192109
192646
  await assertNoMediaSymlinks(path);
192110
- const current2 = await lstat14(path);
192647
+ const current2 = await lstat15(path);
192111
192648
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino || current2.size !== after.size || current2.mtimeMs !== after.mtimeMs) throw fail2(`${role} changed during reading.`);
192112
- return { source: { role, path, bytes: content.length, sha256: createHash13("sha256").update(content).digest("hex") }, content };
192649
+ return { source: { role, path, bytes: content.length, sha256: createHash15("sha256").update(content).digest("hex") }, content };
192113
192650
  } finally {
192114
192651
  await handle.close();
192115
192652
  }
@@ -192122,7 +192659,7 @@ function embed(content, path, kind2) {
192122
192659
  }
192123
192660
  async function exists2(path) {
192124
192661
  try {
192125
- await lstat14(path);
192662
+ await lstat15(path);
192126
192663
  return true;
192127
192664
  } catch (error) {
192128
192665
  if (error.code === "ENOENT") return false;
@@ -192135,22 +192672,22 @@ async function makeParents(root, path, created) {
192135
192672
  const relative2 = parts.slice(0, index).join("/");
192136
192673
  const target = await checkedPath(root, relative2, false);
192137
192674
  try {
192138
- await mkdir11(target, { mode: 448 });
192139
- const info = await lstat14(target);
192675
+ await mkdir12(target, { mode: 448 });
192676
+ const info = await lstat15(target);
192140
192677
  created.push({ path: relative2, dev: info.dev, ino: info.ino, directory: true });
192141
192678
  } catch (error) {
192142
192679
  if (error.code !== "EEXIST") throw error;
192143
- if (!(await lstat14(await checkedPath(root, relative2, false))).isDirectory()) throw fail2("Output parent must be a directory.");
192680
+ if (!(await lstat15(await checkedPath(root, relative2, false))).isDirectory()) throw fail2("Output parent must be a directory.");
192144
192681
  }
192145
192682
  }
192146
192683
  }
192147
192684
  async function cleanCreated2(root, created) {
192148
192685
  for (const item of [...created].reverse()) {
192149
192686
  try {
192150
- const path = await checkedPath(root, item.path, false), info = await lstat14(path);
192687
+ const path = await checkedPath(root, item.path, false), info = await lstat15(path);
192151
192688
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
192152
192689
  if (item.directory) await rmdir2(path);
192153
- else await unlink9(path);
192690
+ else await unlink10(path);
192154
192691
  } catch {
192155
192692
  }
192156
192693
  }
@@ -192175,14 +192712,14 @@ async function prepareMotionComponent(options) {
192175
192712
  if (typeof value !== "string" || !value.trim()) throw fail2(`Required binding ${role} references missing or non-string token ${key}. No demo default was applied.`);
192176
192713
  return [role, value];
192177
192714
  }));
192178
- const fontPath = inputPath(dirname15(input.source.path), document2.fontFile);
192715
+ const fontPath = inputPath(dirname16(input.source.path), document2.fontFile);
192179
192716
  const font = await sourceFile(fontPath, "font", MOTION_INPUT_LIMITS.fontBytes);
192180
192717
  const sources = [input.source, font.source];
192181
192718
  const items = [];
192182
192719
  for (const [index, item] of document2.items.entries()) {
192183
192720
  let image2;
192184
192721
  if (item.imageFile) {
192185
- const path = inputPath(dirname15(input.source.path), item.imageFile);
192722
+ const path = inputPath(dirname16(input.source.path), item.imageFile);
192186
192723
  const file = await sourceFile(path, `items[${index}].image`, MOTION_INPUT_LIMITS.imageBytes);
192187
192724
  image2 = embed(file.content, path, "image");
192188
192725
  sources.push(file.source);
@@ -192223,7 +192760,7 @@ async function prepareMotionComponent(options) {
192223
192760
  resolvedBindings: Object.fromEntries(Object.entries(document2.bindings).map(([role, key]) => [role, { key, value: bound[role], source: resolved.tokenSources[key] }])),
192224
192761
  sources,
192225
192762
  context: { sourceHashes: resolved.lock.sourceHashes, output: resolved.output, mediaPreferences: resolved.mediaPreferences },
192226
- files: { "config.json": { sha256: createHash13("sha256").update(configJson).digest("hex") }, "index.html": { sha256: createHash13("sha256").update(html).digest("hex") } },
192763
+ files: { "config.json": { sha256: createHash15("sha256").update(configJson).digest("hex") }, "index.html": { sha256: createHash15("sha256").update(html).digest("hex") } },
192227
192764
  warnings: resolved.warnings
192228
192765
  };
192229
192766
  const readme = `# EditorBrain motion component
@@ -192243,13 +192780,13 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
192243
192780
  if (await exists2(await productionOutputPath(root, options.outDirectory))) throw new CliError("MOTION_OUTPUT_EXISTS", "The output directory already exists; nothing was overwritten.", "Choose a new directory under .editorbrain-local/.");
192244
192781
  const created = [];
192245
192782
  try {
192246
- await makeParents(root, dirname15(options.outDirectory), created);
192247
- await mkdir11(await productionOutputPath(root, options.outDirectory), { mode: 448 });
192248
- const info = await lstat14(output2);
192783
+ await makeParents(root, dirname16(options.outDirectory), created);
192784
+ await mkdir12(await productionOutputPath(root, options.outDirectory), { mode: 448 });
192785
+ const info = await lstat15(output2);
192249
192786
  created.push({ path: options.outDirectory, dev: info.dev, ino: info.ino, directory: true });
192250
192787
  for (const [name, content] of Object.entries(files)) {
192251
192788
  const path = `${options.outDirectory}/${name}`;
192252
- const handle = await open12(await productionOutputPath(root, path), constants11.O_WRONLY | constants11.O_CREAT | constants11.O_EXCL | constants11.O_NOFOLLOW, 384);
192789
+ const handle = await open13(await productionOutputPath(root, path), constants12.O_WRONLY | constants12.O_CREAT | constants12.O_EXCL | constants12.O_NOFOLLOW, 384);
192253
192790
  try {
192254
192791
  const stat = await handle.stat();
192255
192792
  created.push({ path, dev: stat.dev, ino: stat.ino, directory: false });
@@ -192281,9 +192818,9 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
192281
192818
  }
192282
192819
 
192283
192820
  // packages/cli/src/production-verify.ts
192284
- import { createHash as createHash14, randomUUID as randomUUID6 } from "node:crypto";
192285
- import { mkdir as mkdir12, readFile as readFile8 } from "node:fs/promises";
192286
- import { dirname as dirname16, join as join14, resolve as resolve10 } from "node:path";
192821
+ import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";
192822
+ import { mkdir as mkdir13, readFile as readFile8 } from "node:fs/promises";
192823
+ import { dirname as dirname17, join as join15, resolve as resolve10 } from "node:path";
192287
192824
 
192288
192825
  // packages/cli/src/production-media-review.ts
192289
192826
  function productionMediaReview(resolved) {
@@ -192340,7 +192877,7 @@ function productionEditorialReview(resolved) {
192340
192877
  }
192341
192878
 
192342
192879
  // packages/cli/src/production-verify.ts
192343
- var digest4 = (value) => createHash14("sha256").update(value).digest("hex");
192880
+ var digest4 = (value) => createHash16("sha256").update(value).digest("hex");
192344
192881
  var errorCode2 = (error) => error && typeof error === "object" && "code" in error && typeof error.code === "string" && /^[A-Z0-9_]+$/.test(error.code) ? error.code : "PRODUCTION_VERIFY_FAILED";
192345
192882
  function productionVerificationRequirements(options) {
192346
192883
  const { resolved } = options;
@@ -192374,7 +192911,7 @@ async function sampleFinalArtifact(file, probe2, directory, requested) {
192374
192911
  result2.failures.push({ requestedTimeSeconds: time, code: "MEDIA_SAMPLE_OUT_OF_RANGE" });
192375
192912
  continue;
192376
192913
  }
192377
- const path = join14(directory, `sample-${String(result2.items.length + result2.failures.length + 1).padStart(2, "0")}.png`);
192914
+ const path = join15(directory, `sample-${String(result2.items.length + result2.failures.length + 1).padStart(2, "0")}.png`);
192378
192915
  try {
192379
192916
  const output2 = await runMediaTool("ffmpeg", [
192380
192917
  "-loglevel",
@@ -192446,6 +192983,7 @@ function summarizeProductionVerification(report) {
192446
192983
  visualSheet: report.visualSheet,
192447
192984
  mediaReview: report.mediaReview,
192448
192985
  editorialReview: report.editorialReview,
192986
+ continuity: report.continuity,
192449
192987
  agentInstructions: report.agentInstructions,
192450
192988
  mediaUploaded: false,
192451
192989
  mediaModified: false,
@@ -192456,14 +192994,17 @@ async function verifyProduction(options) {
192456
192994
  const root = await ensureRoot(options.root);
192457
192995
  assertIdentifier(options.resolved.project.id);
192458
192996
  const requirements = productionVerificationRequirements(options);
192997
+ const audioProfile = options.audioProfile === void 0 ? { schemaVersion: 1, ...requirements.loudness ? { loudness: requirements.loudness } : {} } : validateAudioCheckProfile(options.audioProfile);
192998
+ if (requirements.loudness && stableJson(audioProfile.loudness) !== stableJson(requirements.loudness)) throw new CliError("PRODUCTION_REQUIREMENTS_CONFLICT", "Explicit audio profile conflicts with the saved project target.", "Change the project preference explicitly first.");
192999
+ const reviewInput = options.reviewInputs === void 0 ? void 0 : validateContinuityInput(options.reviewInputs);
192459
193000
  if (options.contextVersion !== void 0 && (typeof options.contextVersion !== "string" || !options.contextVersion || options.contextVersion.length > 256 || /[\x00-\x1f\x7f]/.test(options.contextVersion))) throw new CliError("INVALID_CONTEXT_VERSION", "Invalid context version.", "Pass the current project context version.");
192460
193001
  if (options.sampleTimesSeconds !== void 0 && (!Array.isArray(options.sampleTimesSeconds) || options.sampleTimesSeconds.length < 1 || options.sampleTimesSeconds.length > 6 || Array.from(options.sampleTimesSeconds).some((time) => typeof time !== "number" || !Number.isFinite(time) || time < 0 || time > 86400))) throw new CliError("INVALID_SAMPLE_TIMES", "Provide one to six finite sample times between 0 and 86400 seconds.", "Select a few timestamps that answer a review question.");
192461
- const relativeDirectory = options.outDirectory ?? `.editorbrain-local/${options.resolved.project.id}/verify-${randomUUID6()}`;
193002
+ const relativeDirectory = options.outDirectory ?? `.editorbrain-local/${options.resolved.project.id}/verify-${randomUUID7()}`;
192462
193003
  const directory = await productionOutputPath(root, relativeDirectory);
192463
- await mkdir12(dirname16(directory), { recursive: true, mode: 448 });
193004
+ await mkdir13(dirname17(directory), { recursive: true, mode: 448 });
192464
193005
  await productionOutputPath(root, relativeDirectory);
192465
193006
  try {
192466
- await mkdir12(directory, { mode: 448 });
193007
+ await mkdir13(directory, { mode: 448 });
192467
193008
  } catch (error) {
192468
193009
  if (error.code === "EEXIST") throw new CliError("PRODUCTION_OUTPUT_EXISTS", "Verification output already exists; nothing was overwritten.", "Choose a new directory under .editorbrain-local/.");
192469
193010
  throw error;
@@ -192490,6 +193031,7 @@ async function verifyProduction(options) {
192490
193031
  visualSheet: null,
192491
193032
  mediaReview: productionMediaReview(options.resolved),
192492
193033
  editorialReview: productionEditorialReview(options.resolved),
193034
+ continuity: null,
192493
193035
  agentInstructions: [
192494
193036
  "Open the saved sample images and actual final file before making visual or audio claims. Samples have not been viewed automatically.",
192495
193037
  "Reconcile black, silence and peak candidates with the brief. A technical pass never approves storytelling, readability, music/SFX, fonts or synchronization.",
@@ -192518,9 +193060,13 @@ async function verifyProduction(options) {
192518
193060
  report.render = await checkRender({ file, profile: requirements.renderProfile });
192519
193061
  report.artifact = { ...report.render.file, stableAcrossVerification: null };
192520
193062
  const probe2 = report.render.measurements.probe;
192521
- if (requirements.loudness) {
193063
+ if (audioProfile.loudness || probe2?.streams.some((s) => s.type === "audio")) {
192522
193064
  report.audioMeasurement = "checked";
192523
- report.audio = await checkAudio({ file, profile: { schemaVersion: 1, loudness: requirements.loudness } });
193065
+ report.audio = await checkAudio({ file, profile: audioProfile });
193066
+ }
193067
+ if (probe2 && reviewInput) {
193068
+ report.continuity = await checkContinuity(file, probe2.sha256, reviewInput, probe2.durationSeconds);
193069
+ if (report.continuity.missingFaces > 0 || report.continuity.uncoveredOverlays.length > 0 || report.continuity.status === "incomplete" || report.continuity.audio.status === "incomplete" || report.continuity.audio.boundaries.some((b) => b.status === "not_measured")) report.issues.push({ code: "CONTINUITY_CHECK_INCOMPLETE", severity: "incomplete", message: "Requested continuity checks have missing audio/face evidence. Inspect the saved report; no clearance is certified." });
192524
193070
  }
192525
193071
  if (probe2 && report.render.checks.find((check) => check.id === "decode")?.status === "pass") report.samples = await sampleFinalArtifact(file, probe2, directory, options.sampleTimesSeconds);
192526
193072
  if (probe2 && report.samples.status === "complete") {
@@ -192542,9 +193088,9 @@ async function verifyProduction(options) {
192542
193088
  }
192543
193089
  await contextCheck("validAtEnd");
192544
193090
  }
192545
- report.complete = !!report.render?.complete && (!report.audio || report.audio.complete) && report.artifact.stableAcrossVerification === true && report.samples.status === "complete" && !report.issues.length;
193091
+ report.complete = !!report.render?.complete && (!report.audio || !audioProfile.loudness || report.audio.complete) && report.artifact.stableAcrossVerification === true && report.samples.status === "complete" && !report.issues.length;
192546
193092
  const failed = report.issues.some((issue) => issue.severity === "error") || report.render?.technicalStatus === "fail" || report.audio?.technicalStatus === "fail";
192547
- report.technicalStatus = failed ? "fail" : !report.complete ? "incomplete" : report.render?.technicalStatus === "warning" ? "warning" : "pass";
193093
+ report.technicalStatus = failed ? "fail" : !report.complete ? "incomplete" : report.render?.technicalStatus === "warning" || report.audio?.complete === false || report.continuity?.status === "review_required" || report.continuity?.audio.boundaries.some((b) => b.status === "audible_boundary_review") ? "warning" : "pass";
192548
193094
  report.technicalPass = report.complete && !failed;
192549
193095
  const reportPath = await saveProductionReport(root, `${relativeDirectory}/report.json`, report);
192550
193096
  const reportSha256 = digest4(stableJson(report));
@@ -192552,12 +193098,12 @@ async function verifyProduction(options) {
192552
193098
  }
192553
193099
 
192554
193100
  // packages/cli/src/review-artifact.ts
192555
- import { lstat as lstat15, mkdir as mkdir13 } from "node:fs/promises";
192556
- import { basename as basename4, dirname as dirname17, extname as extname6, resolve as resolve11 } from "node:path";
192557
- import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";
193101
+ import { lstat as lstat16, mkdir as mkdir14 } from "node:fs/promises";
193102
+ import { basename as basename4, dirname as dirname18, extname as extname6, resolve as resolve11 } from "node:path";
193103
+ import { createHash as createHash18, randomUUID as randomUUID8 } from "node:crypto";
192558
193104
 
192559
193105
  // packages/cli/src/review-artifact-html.ts
192560
- import { createHash as createHash15 } from "node:crypto";
193106
+ import { createHash as createHash17 } from "node:crypto";
192561
193107
  function reviewApp() {
192562
193108
  const data = JSON.parse(document.getElementById("review-data").textContent);
192563
193109
  const $ = (id3) => document.getElementById(id3);
@@ -192894,9 +193440,9 @@ ${JSON.stringify({ ...feedback(), kind: "editorbrain.review-access-request", dec
192894
193440
  update();
192895
193441
  }
192896
193442
  function renderReviewArtifact(data, wordmark) {
192897
- const script = `(${reviewApp.toString()})();`, hash8 = createHash15("sha256").update(script).digest("base64");
193443
+ const script = `(${reviewApp.toString()})();`, hash9 = createHash17("sha256").update(script).digest("base64");
192898
193444
  const json = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
192899
- return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash8}'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data: blob:; connect-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>EditorBrain \xB7 Tu edici\xF3n</title><style>
193445
+ return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash9}'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data: blob:; connect-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>EditorBrain \xB7 Tu edici\xF3n</title><style>
192900
193446
  *{box-sizing:border-box} [hidden]{display:none!important} :root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:#f6f6f6;background:#090909}body{margin:0;background:radial-gradient(ellipse at 15% 0%,#252525 0,transparent 50%),#090909}main{max-width:1220px;margin:auto;padding:28px clamp(18px,4vw,50px) 44px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #ffffff20;padding-bottom:22px;gap:20px}header svg{width:146px;height:auto;display:block}header span{color:#aaa;font-size:12px}h1{font-size:clamp(28px,4vw,48px);font-weight:550;letter-spacing:-.045em;margin:14px 0}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 12px}.eyebrow{font-size:10px;letter-spacing:.18em;color:#aaa;margin:30px 0 0}.intro{color:#aaa;font-size:15px;line-height:1.6;margin-bottom:24px}button,a{touch-action:manipulation}button{border:1px solid #ffffff30;border-radius:12px;background:#ffffff08;color:#fff;padding:11px 15px;font:inherit;font-size:13px;cursor:pointer}button:hover{background:#ffffff16}button:disabled{opacity:.38;cursor:default}.primary{background:#f5f5f5;color:#111;font-weight:650;border-color:#fff}.primary:hover{background:#ddd}.secondary{background:transparent}button:focus-visible,textarea:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid #fff;outline-offset:4px}p{line-height:1.6}.workspace{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(280px,1fr);gap:30px;align-items:start}.preview{position:sticky;top:20px;min-width:0}.screen{border:1px solid #ffffff22;border-radius:20px;overflow:hidden;background:radial-gradient(ellipse,#242424,#050505);display:flex;justify-content:center;min-height:260px}.screen video{width:100%;max-height:590px;display:block}.controls{display:flex;justify-content:center;align-items:center;gap:16px;margin:12px 0;font-size:12px;color:#aaa;font-variant-numeric:tabular-nums}.controls button{padding:8px 12px}aside{background:linear-gradient(140deg,#ffffff07,#ffffff02);border:1px solid #ffffff19;border-radius:20px;padding:24px}aside>p{color:#aaa;font-size:13px}label{display:block;font-size:12px;color:#bbb}select{max-width:100%;padding:10px;background:#181818;color:#fff;border:1px solid #ffffff40;border-radius:8px}#learning-options article{padding:16px 0;border-top:1px solid #ffffff20}textarea{width:100%;background:#090909;border:1px solid #ffffff30;border-radius:12px;padding:14px;color:#fff;font:inherit;font-size:14px;line-height:1.5;min-height:108px;resize:vertical;margin:12px 0}textarea::placeholder{color:#818181}.target{display:flex;align-items:center;gap:10px;margin:16px 0 0;font-size:12px;color:#bbb;flex-wrap:wrap}.target button{padding:6px 10px}.save{width:100%;margin-bottom:16px}.muted{color:#aaa;font-size:12px}details{border-top:1px solid #ffffff20;padding-top:16px;margin-top:16px}summary{cursor:pointer;font-size:13px;line-height:1.6}#phrases{max-height:300px;overflow-y:auto;margin:12px 0}#phrases article{padding:12px;margin-bottom:8px;border-radius:10px;background:#ffffff04;border-left:2px solid transparent}#phrases .speaking{background:#ffffff12;border-left-color:#fff}#phrases article>button:first-child{border:0;background:none;text-align:left;padding:0;line-height:1.7;width:100%;margin-bottom:8px}#phrases article>button:last-child{font-size:11px;padding:6px 8px}#phrases .removed{opacity:.7}#show-cuts-label{margin:12px 0}#approve{width:100%;margin-top:18px}#pending{padding:12px 16px;border-left:2px solid #eee;background:#ffffff08;font-size:13px;margin-bottom:20px}#notes{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px}#notes article{border:1px solid #ffffff22;border-radius:12px;padding:15px;font-size:13px;overflow-wrap:anywhere}#notes p{margin-bottom:0}.note-head{display:flex;align-items:center;justify-content:space-between;gap:10px}.note-head button{font-size:11px;padding:5px 8px}#markers{display:flex;gap:8px;flex-wrap:wrap}#markers button{font-size:11px;padding:7px 10px}.handoff{margin-top:24px;padding:22px;border:1px solid #ffffff30;border-radius:18px;background:#ffffff05}.handoff-head{display:flex;align-items:center;justify-content:space-between;gap:20px}.handoff p{color:#aaa;font-size:13px;margin:6px 0}.handoff .actions{display:flex;gap:8px;flex-shrink:0;flex-wrap:wrap}#status{color:#fff;margin:14px 0;font-size:13px}#request{font-family:ui-monospace,monospace;font-size:12px;min-height:200px}footer{margin-top:22px;display:flex;justify-content:space-between;gap:16px;color:#888;font-size:11px}#direction-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,250px),1fr));gap:18px}.direction{padding:16px;border:1px solid #ffffff22;border-radius:18px;background:#ffffff05}.direction.chosen{border-color:#fff;box-shadow:0 0 0 1px #fff}.direction img,.direction video{width:100%;height:220px;object-fit:contain;border-radius:10px;background:#030303;margin-bottom:18px}.direction p{color:#bbb;font-size:14px}.direction button{width:100%}.direction details a{display:block;color:#fff;font-size:12px;margin:8px 0}.no-preview{height:160px;display:grid;place-items:center;background:#222;color:#aaa;margin-bottom:16px;border-radius:10px}#future{background:none;border:0;color:#aaa;padding:0;font-size:12px;text-align:left}#future-details{color:#aaa;font-size:13px}#future-details summary{color:#eee}.future-note{max-width:660px}#undo{margin-top:12px}input[type=checkbox]{accent-color:#fff}#intro{max-width:680px}
192901
193447
  @media(max-width:760px){main{padding-top:20px}.workspace{grid-template-columns:1fr;gap:18px}.preview{position:static}.screen video{max-height:52svh}.screen{min-height:180px}aside{padding:20px}.handoff-head{display:block}.actions{margin-top:14px}.actions button{flex:1}.handoff{padding:18px}h1{font-size:32px}#direction-grid{grid-template-columns:1fr}header svg{width:125px}footer{flex-direction:column}#phrases{max-height:260px}}
192902
193448
  @media(prefers-reduced-motion:no-preference){button,.direction{transition:background .15s,border-color .15s}}
@@ -192990,7 +193536,7 @@ async function prepareMedia(root, input, kind2, mediaDir, entries) {
192990
193536
  const mime = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
192991
193537
  if (!mime[extension] || kind2 === "video" && !mime[extension].startsWith("video/")) invalid4("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
192992
193538
  const bytes = await readReviewFile(path, REVIEW_MEDIA_BYTES);
192993
- const sha2562 = createHash16("sha256").update(bytes).digest("hex");
193539
+ const sha2562 = createHash18("sha256").update(bytes).digest("hex");
192994
193540
  if (input.sha256 && input.sha256 !== sha2562) invalid4("Preview hash does not match this version.");
192995
193541
  if (!mediaDir) return { uri: `data:${mime[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime[extension] };
192996
193542
  const name = `${sha2562}${extension}`, file = `${mediaDir}/${name}`;
@@ -193008,7 +193554,7 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
193008
193554
  const target = await productionOutputPath(root, out);
193009
193555
  for (const path of [target, `${target}.review.json`]) {
193010
193556
  try {
193011
- await lstat15(path);
193557
+ await lstat16(path);
193012
193558
  } catch (error) {
193013
193559
  if (error.code === "ENOENT") continue;
193014
193560
  throw error;
@@ -193016,7 +193562,7 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
193016
193562
  invalid4("Review output already exists. Use a new filename; previous decisions are preserved.");
193017
193563
  }
193018
193564
  const entries = [];
193019
- const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID7()}` : void 0;
193565
+ const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID8()}` : void 0;
193020
193566
  const video = input.video ? await prepareMedia(root, input.video, "video", mediaDir, entries) : void 0;
193021
193567
  const directions = input.directions ? [] : void 0;
193022
193568
  for (const { preview, ...direction } of input.directions ?? []) {
@@ -193024,19 +193570,19 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
193024
193570
  }
193025
193571
  const clean = { schemaVersion: 1, projectId: input.projectId, title: input.title, version: input.version, stage: input.stage, ...input.contextVersion ? { contextVersion: input.contextVersion } : {}, ...video ? { video } : {}, ...directions ? { directions } : {}, ...input.transcript ? { transcript: input.transcript } : {}, ...input.learnings ? { learnings: input.learnings } : {}, ...input.learningContext ? { learningContext: input.learningContext } : {} };
193026
193572
  if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid4("Embedded previews exceed 40 MiB. Use smaller review copies.");
193027
- const artifactId = createHash16("sha256").update(JSON.stringify(clean)).digest("hex");
193573
+ const artifactId = createHash18("sha256").update(JSON.stringify(clean)).digest("hex");
193028
193574
  const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
193029
- await mkdir13(dirname17(target), { recursive: true });
193575
+ await mkdir14(dirname18(target), { recursive: true });
193030
193576
  await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
193031
- if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, html: { file: out, sha256: createHash16("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
193577
+ if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, html: { file: out, sha256: createHash18("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
193032
193578
  return { kind: "editorbrain.review-artifact", path: target, artifactId, projectId: input.projectId, stage: input.stage, videoSha256: video?.sha256 ?? null, mediaEmbedded: mediaMode === "embedded", htmlBytes: Buffer.byteLength(html), mediaBytes: entries.reduce((sum, item) => sum + item.bytes, 0), ...mediaMode === "local" ? { openCommand: { executable: "editorbrain", args: ["production", "review-open", "--file", out, "--dir", root] } } : {}, mediaUploaded: false, agentTriggered: false, reviewSurface: "computer", cloudStorageBytes: 0, next: mediaMode === "local" ? "Run openCommand as a persistent preview process. Open its verified URL in the Claude Code Desktop Browser pane or the host browser. Keep the process alive; verify video playback, seeking and comments before delivery. Do not attach this HTML alone or publish it as a native Claude artifact: its private media are separate. No upload. Clicks do not wake the agent." : "Standalone embedded export: inspect htmlBytes before attaching. Host size/playback limits vary; if rejected, regenerate with --media-mode local and use production review-open. Never paste the base64 file into model context. No upload or automatic agent wake-up." };
193033
193579
  }
193034
193580
 
193035
193581
  // packages/cli/src/review-server.ts
193036
193582
  import { createServer as createServer2 } from "node:http";
193037
- import { createHash as createHash17, randomBytes as randomBytes2 } from "node:crypto";
193583
+ import { createHash as createHash19, randomBytes as randomBytes2 } from "node:crypto";
193038
193584
  import { basename as basename5 } from "node:path";
193039
- var hash6 = (bytes) => createHash17("sha256").update(bytes).digest("hex");
193585
+ var hash7 = (bytes) => createHash19("sha256").update(bytes).digest("hex");
193040
193586
  var invalid5 = () => new CliError("INVALID_LOCAL_REVIEW", "The local review or its media is missing, altered or unsupported.", "Regenerate with production review-artifact --media-mode local using a new output path. Keep the HTML, .review.json and media folder together.");
193041
193587
  var validHash = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
193042
193588
  async function startReviewArtifact(root, file, port = 0) {
@@ -193046,7 +193592,7 @@ async function startReviewArtifact(root, file, port = 0) {
193046
193592
  const manifest = JSON.parse((await readReviewFile(manifestPath, 64 * 1024)).toString());
193047
193593
  if (manifest?.schemaVersion !== 1 || manifest.kind !== "editorbrain.local-review" || !validHash(manifest.artifactId) || manifest.html?.file !== file || !validHash(manifest.html.sha256) || !Array.isArray(manifest.media) || manifest.media.length > 3) throw invalid5();
193048
193594
  const html = await readReviewFile(await productionOutputPath(root, file), 2 * 1024 * 1024);
193049
- if (hash6(html) !== manifest.html.sha256 || html.length !== manifest.html.bytes) throw invalid5();
193595
+ if (hash7(html) !== manifest.html.sha256 || html.length !== manifest.html.bytes) throw invalid5();
193050
193596
  const resources = /* @__PURE__ */ new Map();
193051
193597
  resources.set("index.html", { body: html, mime: "text/html; charset=utf-8" });
193052
193598
  const mime = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
@@ -193058,7 +193604,7 @@ async function startReviewArtifact(root, file, port = 0) {
193058
193604
  const uri = `${encodeURIComponent(basename5(file) + ".media-" + match[1])}/${match[2]}.${match[3]}`;
193059
193605
  if (entry.uri !== uri || resources.has(uri)) throw invalid5();
193060
193606
  const bytes = await readReviewFile(await productionOutputPath(root, entry.file), REVIEW_MEDIA_BYTES);
193061
- if (bytes.length !== entry.bytes || hash6(bytes) !== entry.sha256) throw invalid5();
193607
+ if (bytes.length !== entry.bytes || hash7(bytes) !== entry.sha256) throw invalid5();
193062
193608
  resources.set(uri, { body: bytes, mime: entry.mimeType });
193063
193609
  }
193064
193610
  const token = randomBytes2(24).toString("hex"), prefix = `/${token}/`;
@@ -193129,7 +193675,7 @@ async function startReviewArtifact(root, file, port = 0) {
193129
193675
  });
193130
193676
  try {
193131
193677
  const probe2 = await fetch(url2, { signal: AbortSignal.timeout(5e3) });
193132
- if (probe2.status !== 200 || hash6(Buffer.from(await probe2.arrayBuffer())) !== manifest.html.sha256) throw invalid5();
193678
+ if (probe2.status !== 200 || hash7(Buffer.from(await probe2.arrayBuffer())) !== manifest.html.sha256) throw invalid5();
193133
193679
  } catch (error) {
193134
193680
  await close();
193135
193681
  throw error;
@@ -193155,7 +193701,7 @@ var uuid2 = (value, name) => {
193155
193701
  if (typeof value !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)) invalid6(`${name} must be a revision or feedback UUID.`);
193156
193702
  return value;
193157
193703
  };
193158
- var hash7 = (value, name) => {
193704
+ var hash8 = (value, name) => {
193159
193705
  if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid6(`${name} must be an exact SHA-256 hash.`);
193160
193706
  return value;
193161
193707
  };
@@ -193168,7 +193714,7 @@ function reviewBody(value, command) {
193168
193714
  const fields = command === "sample" ? ["assetId", "contextVersion", "title", "notes", "parentRevisionId", "revisionId", "transcript"] : ["resultRevisionId", "contextVersion", "resultNote", "preservedElements"];
193169
193715
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !fields.includes(key))) invalid6("Use only documented review fields; project and feedback IDs come from command flags, never the JSON body.");
193170
193716
  const body = value;
193171
- hash7(body.contextVersion, "contextVersion");
193717
+ hash8(body.contextVersion, "contextVersion");
193172
193718
  if (command === "sample") {
193173
193719
  if (body.transcript !== void 0) {
193174
193720
  try {
@@ -193177,7 +193723,7 @@ function reviewBody(value, command) {
193177
193723
  invalid6(e.message);
193178
193724
  }
193179
193725
  }
193180
- hash7(body.assetId, "assetId");
193726
+ hash8(body.assetId, "assetId");
193181
193727
  text11(body.title, "title", 120);
193182
193728
  text11(body.notes, "notes", 2e3, true);
193183
193729
  for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0) uuid2(body[key], key);
@@ -193211,7 +193757,7 @@ async function productionReviewCommand(client, root, command, flags) {
193211
193757
  assertIdentifier(projectId);
193212
193758
  const base = `/v1/projects/${encodeURIComponent(projectId)}`;
193213
193759
  const revision2 = () => encodeURIComponent(uuid2(required("revision"), "--revision"));
193214
- const contextVersion = () => hash7(required("context-version"), "--context-version");
193760
+ const contextVersion = () => hash8(required("context-version"), "--context-version");
193215
193761
  const after = flags.after === void 0 ? void 0 : uuid2(required("after"), "--after");
193216
193762
  if (command === "transcript") return client.request(`${base}/production-reviews/${revision2()}/transcript`);
193217
193763
  if (command === "reviews") return client.request(`${base}/production-reviews${after ? "?" + new URLSearchParams({ after }) : ""}`);
@@ -193344,9 +193890,13 @@ editorbrain library media <video-id> --sha256 media-hash --out file
193344
193890
  editorbrain narrative search [query] [--kind hook|cta|...] [--channel visual|spoken|...] [--limit 10]
193345
193891
  editorbrain narrative get <video-id> [--sha256 document-hash] [--event-offset 0] [--relation-offset 0] [--limit 50]
193346
193892
  editorbrain styles list
193893
+ editorbrain styles mine [--dir folder]
193894
+ editorbrain variants create ID --project BASE --file changes.json [--dir folder]
193895
+ editorbrain variants list --project BASE [--dir folder]
193896
+ editorbrain clean --project ID [--dir folder] [--deduplicate --confirm]
193347
193897
  editorbrain styles source <id> --style-version <v> --out <archive> [--dir folder]
193348
193898
  editorbrain styles prepare <id> --style-version <v> --file <archive> --out <new-directory> [--dir folder]
193349
- editorbrain styles create <style-id> [--from-project project-id] [--name name] [--dir folder]
193899
+ editorbrain styles create <style-id> [--from-project project-id] [--scene scene.html] [--name name] [--dir folder]
193350
193900
  editorbrain styles push <style-id> [--with-resources] [--dry-run] [--dir folder]
193351
193901
  editorbrain styles pull <style-id> [--dry-run] [--dir folder]
193352
193902
  editorbrain styles test <style-id> --project project-id [--dir folder]
@@ -193355,7 +193905,7 @@ editorbrain styles component prepare --style ID --id ID --parameters params.json
193355
193905
  editorbrain styles component list --style ID [--dir folder]
193356
193906
  editorbrain media style create <style-id> --style <style-id> --file recipe.json [--dir folder]
193357
193907
  editorbrain styles captions create --style ID --file captions.json [--dir folder]
193358
- editorbrain styles captions prepare --project ID [--style ID] --file cues.json --out new.html [--dir folder]
193908
+ editorbrain styles captions prepare [--project ID] [--style ID] --file cues.json --out new.html [--dir folder]
193359
193909
  editorbrain styles techniques create --style ID --file techniques.json [--dir folder]
193360
193910
  editorbrain styles check <style-id> [--dir folder]
193361
193911
  editorbrain media styles [--category image|motion]
@@ -193380,7 +193930,7 @@ editorbrain production matte-check --file montage.mp4 --mask-file mask.mp4 [--di
193380
193930
  editorbrain production matte --engine apple-vision --file montage.mp4 --out .editorbrain-local/new-matte [--dir folder]
193381
193931
  editorbrain production matte-plan --file montage.mp4 [--dir folder]
193382
193932
  editorbrain production check --file render [--profile local-profile.json] [--dir folder] [--out .editorbrain-local/report.json] [--details]
193383
- editorbrain production verify --project ID --file final.mp4 [--platform tiktok|reels|shorts] [--profile geometry.json] [--duration seconds] [--at 0,5,12] [--dir folder] [--out .editorbrain-local/new-check] [--offline] [--details]
193933
+ editorbrain production verify --project ID --file final.mp4 [--audio-profile audio.json] [--review-inputs continuity.json] [--platform tiktok|reels|shorts] [--profile geometry.json] [--duration seconds] [--at 0,5,12] [--dir folder] [--out .editorbrain-local/new-check] [--offline] [--details]
193384
193934
  editorbrain production review-artifact --file review.json --out .editorbrain-local/review-v1.html [--media-mode local|embedded] [--dir folder]
193385
193935
  editorbrain production review-open --file .editorbrain-local/review-v1.html [--port 0] [--dir folder]
193386
193936
  editorbrain production reviews --project ID [--after UUID]
@@ -193427,8 +193977,8 @@ function parseArgs(argv) {
193427
193977
  const positional = [];
193428
193978
  const flags = {};
193429
193979
  const motionFilters = /* @__PURE__ */ new Map();
193430
- const booleans = /* @__PURE__ */ new Set(["with-resources", "tresD", "remote", "global", "shared", "matte", "local", "include-unverified", "help", "version", "offline", "dry-run", "key-stdin", "invite-stdin", "no-browser", "skip-mcp", "all", "share-authorized", "details", "include-unknown", "reviewed", "user-confirmed", "confirm"]);
193431
- const known = /* @__PURE__ */ new Set(["from-project", "scene", "bindings", "parameters", "hook-end", "context-hash", "segment", "engine", "mask-file", "platform", "voice", "cues", "bank", "scene-role", "catalog-sha256", "quality", "purpose", "source-sha256", "ids", "max-credits", "audio-stream", "manifest", "query", "provider", "licenses", "input", "max-files", "at", "profile", "inventory", "plan", "dir", "brand", "style", "project", "topic", "goal", "name", "adapter", "out", "url", "document", "mime", "label", "role", "limit", "cursor", "timeout", "assets", "capabilities", "duration", "agent", "workspace", "prefix", "sha256", "kind", "channel", "epistemic-status", "event-offset", "relation-offset", "script", "video", "asset", "requirements", "mode", "review", "previous-version", "previous-context-version", "category", "style-version", "file", "revision", "expected-revision", "before", "scope", "id", "text", "conditions", "status", "index", "title", "days", ...booleans]);
193980
+ const booleans = /* @__PURE__ */ new Set(["deduplicate", "with-resources", "tresD", "remote", "global", "shared", "matte", "local", "include-unverified", "help", "version", "offline", "dry-run", "key-stdin", "invite-stdin", "no-browser", "skip-mcp", "all", "share-authorized", "details", "include-unknown", "reviewed", "user-confirmed", "confirm"]);
193981
+ const known = /* @__PURE__ */ new Set(["review-inputs", "audio-profile", "from-project", "scene", "bindings", "parameters", "hook-end", "context-hash", "segment", "engine", "mask-file", "platform", "voice", "cues", "bank", "scene-role", "catalog-sha256", "quality", "purpose", "source-sha256", "ids", "max-credits", "audio-stream", "manifest", "query", "provider", "licenses", "input", "max-files", "at", "profile", "inventory", "plan", "dir", "brand", "style", "project", "topic", "goal", "name", "adapter", "out", "url", "document", "mime", "label", "role", "limit", "cursor", "timeout", "assets", "capabilities", "duration", "agent", "workspace", "prefix", "sha256", "kind", "channel", "epistemic-status", "event-offset", "relation-offset", "script", "video", "asset", "requirements", "mode", "review", "previous-version", "previous-context-version", "category", "style-version", "file", "revision", "expected-revision", "before", "scope", "id", "text", "conditions", "status", "index", "title", "days", ...booleans]);
193432
193982
  known.add("material");
193433
193983
  known.add("funcion");
193434
193984
  known.add("encuadre");
@@ -193481,16 +194031,16 @@ function output(value) {
193481
194031
  process.stdout.write(stableJson(value));
193482
194032
  }
193483
194033
  async function configRoot(create = false) {
193484
- let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join15(homedir3(), ".config", "editorbrain");
194034
+ let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join16(homedir3(), ".config", "editorbrain");
193485
194035
  if (!create && !process.env.EDITORBRAIN_CONFIG_DIR && !process.env.EDITORHARNESS_CONFIG_DIR) {
193486
194036
  try {
193487
- await lstat16(path);
194037
+ await lstat17(path);
193488
194038
  } catch (error) {
193489
194039
  if (error.code !== "ENOENT") throw error;
193490
- path = join15(homedir3(), ".config", "editorharness");
194040
+ path = join16(homedir3(), ".config", "editorharness");
193491
194041
  }
193492
194042
  }
193493
- if (create) await mkdir14(path, { recursive: true, mode: 448 });
194043
+ if (create) await mkdir15(path, { recursive: true, mode: 448 });
193494
194044
  return ensureRoot(path);
193495
194045
  }
193496
194046
  async function loadConfig() {
@@ -193507,7 +194057,7 @@ async function loadConfig() {
193507
194057
  async function saveConfig(config2) {
193508
194058
  const root = await configRoot(true);
193509
194059
  await atomicWrite(root, "config.json", stableJson(config2), { document: false, mode: 384 });
193510
- await chmod2(join15(root, "config.json"), 384);
194060
+ await chmod3(join16(root, "config.json"), 384);
193511
194061
  }
193512
194062
  async function config(args, requireKey = true) {
193513
194063
  const stored = await loadConfig();
@@ -193536,7 +194086,7 @@ async function init(args) {
193536
194086
  for (const path of Object.keys(files)) {
193537
194087
  const target = await checkedPath(root, path);
193538
194088
  try {
193539
- await lstat16(target);
194089
+ await lstat17(target);
193540
194090
  throw new Error(`Refusing to replace existing file: ${path}`);
193541
194091
  } catch (error) {
193542
194092
  if (error.code !== "ENOENT") throw error;
@@ -193548,13 +194098,13 @@ async function init(args) {
193548
194098
  for (const path of directories) {
193549
194099
  const target = await checkedPath(root, path, false);
193550
194100
  try {
193551
- if (!(await lstat16(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
194101
+ if (!(await lstat17(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
193552
194102
  } catch (error) {
193553
194103
  if (error.code !== "ENOENT") throw error;
193554
194104
  }
193555
194105
  }
193556
194106
  for (const [path, content] of Object.entries(files)) await atomicWrite(root, path, content, { overwrite: false });
193557
- for (const path of directories) await mkdir14(await checkedPath(root, path, false), { recursive: true });
194107
+ for (const path of directories) await mkdir15(await checkedPath(root, path, false), { recursive: true });
193558
194108
  const guidance2 = await installGuidance();
193559
194109
  try {
193560
194110
  await rememberGuidance(guidance2);
@@ -193616,7 +194166,7 @@ async function main() {
193616
194166
  if (args.flags["dry-run"] && !["push", "pull", "update"].includes(command) && !(command === "onboarding" && ["apply", "sync"].includes(subcommand)) && !(command === "styles" && ["push", "pull"].includes(subcommand))) throw new CliError("INVALID_ARGUMENT", "--dry-run is supported by push, pull, update, styles push/pull and onboarding apply/sync.", "Read editorbrain help.");
193617
194167
  if (args.flags.offline && command !== "doctor" && !(command === "production" && ["verify", "mix-events"].includes(subcommand))) throw new CliError("INVALID_ARGUMENT", "--offline is supported by doctor, production verify and project-scoped mix-events.", "Read editorbrain help.");
193618
194168
  if (!command || command === "help" || args.flags.help) {
193619
- process.stdout.write(HELP);
194169
+ process.stdout.write(commandHelp(HELP, command === "help" ? args.positional.slice(1) : args.flags.help ? args.positional : []));
193620
194170
  return;
193621
194171
  }
193622
194172
  if (args.flags.details && !["media", "production", "integrations"].includes(command) && !(command === "search" && subcommand === "brief")) throw new CliError("INVALID_ARGUMENT", "--details is supported only by media, production, integrations list and search brief.", "Read editorbrain help.");
@@ -193888,7 +194438,7 @@ async function main() {
193888
194438
  if (hookEnd !== void 0 && (!hookEnd.trim() || !Number.isFinite(Number(hookEnd)) || Number(hookEnd) < 0)) throw new Error("--hook-end must be nonnegative final seconds.");
193889
194439
  const credentials = projectId && !args.flags.offline ? await config(args, false) : void 0;
193890
194440
  const context = projectId ? await prepareProductionContext(root2, projectId, credentials?.apiKey ? new Client(credentials) : void 0) : void 0;
193891
- output(await mixEvents({ root: root2, voice: resolve12(root2, voice), manifest: await readProductionJson(root2, cues), manifestDirectory: dirname18(resolve12(root2, cues)), out, context, hookEndSeconds: hookEnd === void 0 ? void 0 : Number(hookEnd) }));
194441
+ output(await mixEvents({ root: root2, voice: resolve12(root2, voice), manifest: await readProductionJson(root2, cues), manifestDirectory: dirname19(resolve12(root2, cues)), out, context, hookEndSeconds: hookEnd === void 0 ? void 0 : Number(hookEnd) }));
193892
194442
  return;
193893
194443
  }
193894
194444
  if (command === "production" && ["review-sheet", "matte", "matte-plan", "matte-engines", "matte-check"].includes(subcommand)) {
@@ -193915,7 +194465,7 @@ async function main() {
193915
194465
  }
193916
194466
  if (command === "production" && subcommand === "verify") {
193917
194467
  if (argument) throw new CliError("INVALID_ARGUMENT", "Use named flags for production verify.", "Read editorbrain help.");
193918
- const allowed = /* @__PURE__ */ new Set(["project", "file", "duration", "at", "dir", "out", "offline", "details", "url", "profile", "platform"]);
194468
+ const allowed = /* @__PURE__ */ new Set(["project", "file", "duration", "at", "dir", "out", "offline", "details", "url", "profile", "platform", "audio-profile", "review-inputs"]);
193919
194469
  for (const flag2 of Object.keys(args.flags)) if (!allowed.has(flag2)) throw new CliError("INVALID_ARGUMENT", `--${flag2} is not supported for production verify.`, "Read editorbrain help.");
193920
194470
  const projectId = str(args, "project"), file = str(args, "file");
193921
194471
  if (!projectId || !file) throw new CliError("INVALID_ARGUMENT", "--project and --file are required.", "Read editorbrain help.");
@@ -193929,7 +194479,7 @@ async function main() {
193929
194479
  const client = credentials?.apiKey ? new Client(credentials) : void 0;
193930
194480
  await withWorkspaceLock(root2, async () => {
193931
194481
  const context = await prepareProductionContext(root2, projectId, client);
193932
- const result2 = await verifyProduction({ root: root2, file, ...context, platform: str(args, "platform"), visualProfile: str(args, "profile") ? await readProductionJson(root2, str(args, "profile")) : void 0, ...str(args, "out") ? { outDirectory: str(args, "out") } : {}, ...str(args, "duration") !== void 0 ? { expectedDurationSeconds: Number(str(args, "duration")) } : {}, ...times ? { sampleTimesSeconds: times.map(Number) } : {} });
194482
+ const result2 = await verifyProduction({ root: root2, file, ...context, audioProfile: str(args, "audio-profile") ? await readProductionJson(root2, str(args, "audio-profile")) : void 0, reviewInputs: str(args, "review-inputs") ? await loadContinuityInput(root2, str(args, "review-inputs")) : void 0, platform: str(args, "platform"), visualProfile: str(args, "profile") ? await readProductionJson(root2, str(args, "profile")) : void 0, ...str(args, "out") ? { outDirectory: str(args, "out") } : {}, ...str(args, "duration") !== void 0 ? { expectedDurationSeconds: Number(str(args, "duration")) } : {}, ...times ? { sampleTimesSeconds: times.map(Number) } : {} });
193933
194483
  output({ ...args.flags.details ? result2.report : result2.summary, contextScope: context.contextScope, reportPath: result2.reportPath, reportSha256: result2.reportSha256 });
193934
194484
  if (result2.report.technicalStatus === "fail") process.exitCode = 1;
193935
194485
  else if (!result2.report.complete) process.exitCode = 2;
@@ -194106,7 +194656,7 @@ async function main() {
194106
194656
  }
194107
194657
  if (subcommand === "captions" && argument === "prepare") {
194108
194658
  valid(3, ["project", "style", "file", "out"]);
194109
- if (!str(args, "project") || !str(args, "file") || !str(args, "out")) throw new Error("Use styles captions prepare --project ID [--style ID] --file cues.json --out new.html");
194659
+ if (!str(args, "project") && !str(args, "style") || !str(args, "file") || !str(args, "out")) throw new Error("Use styles captions prepare [--project ID] [--style ID] --file cues.json --out new.html");
194110
194660
  output(await prepareCaptions(directory, str(args, "project"), str(args, "file"), str(args, "out"), str(args, "style")));
194111
194661
  return;
194112
194662
  }
@@ -194116,13 +194666,29 @@ async function main() {
194116
194666
  output(await saveStyleContract(directory, id3, command === "media" ? "media-style.json" : subcommand === "captions" ? "captions.json" : "techniques.json", file));
194117
194667
  return;
194118
194668
  }
194669
+ if (command === "variants") {
194670
+ if (!str(args, "project") || !["create", "list"].includes(subcommand) || args.positional.length !== (subcommand === "create" ? 3 : 2) || Object.keys(args.flags).some((k) => !["project", "dir", ...subcommand === "create" ? ["file"] : []].includes(k))) throw new CliError("INVALID_ARGUMENT", "Use variants create ID --project BASE --file changes.json or variants list --project BASE.", "Run variants --help.");
194671
+ const root2 = await ensureRoot(str(args, "dir") ?? process.cwd());
194672
+ output(await projectVariants(root2, str(args, "project"), subcommand, argument, str(args, "file") ? await readProductionJson(root2, str(args, "file")) : void 0));
194673
+ return;
194674
+ }
194675
+ if (command === "clean") {
194676
+ if (args.positional.length !== 1 || !str(args, "project") || Object.keys(args.flags).some((k) => !["project", "dir", "deduplicate", "confirm"].includes(k))) throw new CliError("INVALID_ARGUMENT", "Use clean --project ID [--deduplicate --confirm].", "Start with inspection; this command never removes originals or renders.");
194677
+ output(await cleanProject(str(args, "dir") ?? process.cwd(), str(args, "project"), { deduplicate: !!args.flags.deduplicate, confirm: !!args.flags.confirm }));
194678
+ return;
194679
+ }
194680
+ if (command === "styles" && subcommand === "mine") {
194681
+ if (args.positional.length !== 2 || Object.keys(args.flags).some((k) => k !== "dir")) throw new CliError("INVALID_ARGUMENT", "Use styles mine [--dir folder].", "This lists local styles; styles list queries the published library.");
194682
+ output(await listLocalStyles(str(args, "dir") ?? process.cwd()));
194683
+ return;
194684
+ }
194119
194685
  if (command === "styles" && (subcommand === "create" || subcommand === "check")) {
194120
- const allowed = new Set(subcommand === "create" ? ["dir", "name", "from-project"] : ["dir"]);
194686
+ const allowed = new Set(subcommand === "create" ? ["dir", "name", "from-project", "scene"] : ["dir"]);
194121
194687
  if (args.positional.length !== 3 && !(subcommand === "create" && args.positional.length === 2 && str(args, "from-project")) || Object.keys(args.flags).some((flag2) => !allowed.has(flag2))) {
194122
194688
  throw new CliError("INVALID_ARGUMENT", `Use styles ${subcommand} <style-id> [--dir folder]${subcommand === "create" ? " [--name name]" : ""}.`, "Style authoring runs locally and accepts only the documented options.");
194123
194689
  }
194124
194690
  const options = { directory: str(args, "dir") ?? process.cwd(), id: argument ?? `${str(args, "from-project")}-style` };
194125
- if (subcommand === "create") output(await createLocalStyle({ ...options, name: str(args, "name"), fromProject: str(args, "from-project") }));
194691
+ if (subcommand === "create") output(await createLocalStyle({ ...options, name: str(args, "name"), fromProject: str(args, "from-project"), scene: str(args, "scene") }));
194126
194692
  else {
194127
194693
  const result2 = await checkLocalStyle(options);
194128
194694
  output(result2);
@@ -194158,7 +194724,7 @@ async function main() {
194158
194724
  const outRoot = await ensureRoot(resolve12(str(args, "dir") ?? process.cwd(), destination), true);
194159
194725
  for (const path of Object.keys(result2.files)) {
194160
194726
  try {
194161
- await lstat16(await checkedPath(outRoot, path, false));
194727
+ await lstat17(await checkedPath(outRoot, path, false));
194162
194728
  throw new Error(`Refusing to replace existing proposal: ${path}`);
194163
194729
  } catch (error) {
194164
194730
  if (error.code !== "ENOENT") throw error;
@@ -194184,7 +194750,7 @@ async function main() {
194184
194750
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(result2.id) || typeof result2.apiKey !== "string") throw new Error("Invalid key response");
194185
194751
  const file = `keys/${result2.id}.json`;
194186
194752
  await atomicWrite(root2, file, stableJson({ url: client.url, apiKey: result2.apiKey, id: result2.id, label, role }), { document: false, mode: 384, overwrite: false });
194187
- output({ id: result2.id, label, role, credentialFile: join15(root2, file) });
194753
+ output({ id: result2.id, label, role, credentialFile: join16(root2, file) });
194188
194754
  return;
194189
194755
  }
194190
194756
  if (subcommand === "revoke" && argument) {
@@ -194315,7 +194881,7 @@ async function main() {
194315
194881
  }
194316
194882
  if (subcommand === "upload" && argument) {
194317
194883
  const target = resolve12(str(args, "dir") ?? process.cwd(), argument);
194318
- const handle = await open13(target, constants12.O_RDONLY | constants12.O_NOFOLLOW);
194884
+ const handle = await open14(target, constants13.O_RDONLY | constants13.O_NOFOLLOW);
194319
194885
  let bytes;
194320
194886
  try {
194321
194887
  const info = await handle.stat();
@@ -194327,22 +194893,22 @@ async function main() {
194327
194893
  const types2 = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg" };
194328
194894
  const mimeType = str(args, "mime") ?? types2[extname7(target).toLowerCase()];
194329
194895
  if (!mimeType) throw new Error("Unsupported extension; specify --mime for a supported media format");
194330
- const hash8 = await sha256(bytes);
194896
+ const hash9 = await sha256(bytes);
194331
194897
  const params = new URLSearchParams({ name: basename6(target) });
194332
194898
  if (str(args, "project")) params.set("projectId", str(args, "project"));
194333
194899
  if (str(args, "purpose")) params.set("purpose", str(args, "purpose"));
194334
194900
  if (str(args, "source-sha256")) params.set("sourceSha256", str(args, "source-sha256"));
194335
- const path = `/v1/assets/${hash8}?${params}`;
194901
+ const path = `/v1/assets/${hash9}?${params}`;
194336
194902
  const result2 = str(args, "purpose") === "preview" ? await client.uploadPreview(path, bytes, mimeType) : await client.media(path, { content: bytes, mimeType });
194337
194903
  const body = await result2.json();
194338
- if (body.sha256 !== hash8) throw new Error("Upload response hash mismatch");
194904
+ if (body.sha256 !== hash9) throw new Error("Upload response hash mismatch");
194339
194905
  output(body);
194340
194906
  return;
194341
194907
  }
194342
194908
  if (subcommand === "download" && argument && str(args, "out")) {
194343
194909
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
194344
194910
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
194345
- const root2 = await ensureRoot(dirname18(destination), true);
194911
+ const root2 = await ensureRoot(dirname19(destination), true);
194346
194912
  await checkedPath(root2, basename6(destination), false);
194347
194913
  const response = await client.media(`/v1/assets/${argument}`);
194348
194914
  const bytes = new Uint8Array(await response.arrayBuffer());
@@ -194403,7 +194969,7 @@ async function main() {
194403
194969
  if (command === "search" && subcommand === "brief") {
194404
194970
  const path = str(args, "file");
194405
194971
  if (!path) throw new Error("Provide --file with the editorial brief JSON after inspecting the actual material.");
194406
- const handle = await open13(resolve12(path), constants12.O_RDONLY | constants12.O_NOFOLLOW);
194972
+ const handle = await open14(resolve12(path), constants13.O_RDONLY | constants13.O_NOFOLLOW);
194407
194973
  let brief;
194408
194974
  try {
194409
194975
  const stat = await handle.stat();
@@ -194425,7 +194991,7 @@ async function main() {
194425
194991
  const scriptPath = str(args, "script"), videoPath = str(args, "video");
194426
194992
  let script, assetId = str(args, "asset");
194427
194993
  const readInput = async (path, max) => {
194428
- const handle = await open13(resolve12(path), constants12.O_RDONLY | constants12.O_NOFOLLOW);
194994
+ const handle = await open14(resolve12(path), constants13.O_RDONLY | constants13.O_NOFOLLOW);
194429
194995
  try {
194430
194996
  const stat = await handle.stat();
194431
194997
  if (!stat.isFile() || stat.size < 1 || stat.size > max) throw new Error(`Input must be a regular file of at most ${max} bytes.`);
@@ -194481,20 +195047,20 @@ async function main() {
194481
195047
  }
194482
195048
  if (subcommand === "get" && argument) {
194483
195049
  const document2 = str(args, "document");
194484
- const hash8 = str(args, "sha256");
194485
- if (hash8 && !document2) throw new Error("--sha256 requires --document for library get.");
194486
- const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash8 ? { sha256: hash8 } : {} })}` : ""}`);
194487
- if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash8 && result2.sha256 !== hash8)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
195050
+ const hash9 = str(args, "sha256");
195051
+ if (hash9 && !document2) throw new Error("--sha256 requires --document for library get.");
195052
+ const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash9 ? { sha256: hash9 } : {} })}` : ""}`);
195053
+ if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash9 && result2.sha256 !== hash9)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
194488
195054
  output(result2);
194489
195055
  return;
194490
195056
  }
194491
195057
  if (subcommand === "media" && argument && str(args, "out")) {
194492
- const hash8 = str(args, "sha256");
194493
- if (!hash8 || !/^[a-f0-9]{64}$/.test(hash8)) throw new Error("--sha256 must be a media SHA-256 from library get.");
195058
+ const hash9 = str(args, "sha256");
195059
+ if (!hash9 || !/^[a-f0-9]{64}$/.test(hash9)) throw new Error("--sha256 must be a media SHA-256 from library get.");
194494
195060
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
194495
- const root2 = await ensureRoot(dirname18(destination), true);
195061
+ const root2 = await ensureRoot(dirname19(destination), true);
194496
195062
  await checkedPath(root2, basename6(destination), false);
194497
- const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash8}`);
195063
+ const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash9}`);
194498
195064
  const reader = response.body?.getReader();
194499
195065
  if (!reader) throw new Error("Media body missing.");
194500
195066
  const chunks = [];
@@ -194510,9 +195076,9 @@ async function main() {
194510
195076
  chunks.push(value);
194511
195077
  }
194512
195078
  const bytes = Buffer.concat(chunks);
194513
- if (await sha256(bytes) !== hash8) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
195079
+ if (await sha256(bytes) !== hash9) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
194514
195080
  await atomicWrite(root2, basename6(destination), bytes, { document: false, overwrite: false });
194515
- output({ videoId: argument, path: destination, sha256: hash8, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
195081
+ output({ videoId: argument, path: destination, sha256: hash9, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
194516
195082
  return;
194517
195083
  }
194518
195084
  throw new Error("Use library search, library get, or library media <video-id> --sha256 hash --out file.");