editorbrain 0.42.0 → 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
  }
@@ -216,6 +219,7 @@ function checkStyle(files, id3) {
216
219
  var obj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
217
220
  var text = (v) => typeof v === "string" && v.trim().length > 0 && v.length <= 8e3;
218
221
  var id = (v) => typeof v === "string" && /^[a-z0-9][a-z0-9_-]{0,79}$/.test(v) && !["constructor", "prototype", "__proto__"].includes(v);
222
+ var bindingName = (v) => typeof v === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(v) && !["constructor", "prototype", "__proto__"].includes(v);
219
223
  var texts = (v) => Array.isArray(v) && v.length <= 100 && v.every(text);
220
224
  var ids = (v) => Array.isArray(v) && v.length <= 100 && v.every(id) && new Set(v).size === v.length;
221
225
  var unit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
@@ -228,7 +232,7 @@ function styleReuseIssues(name, value, expectedId) {
228
232
  const fields = (v, allowed, label) => {
229
233
  if (obj(v) && Object.keys(v).some((k) => !allowed.includes(k))) add(`${label} has unsupported fields; store only the documented contract, never credentials.`);
230
234
  };
231
- 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"] };
232
236
  fields(value, ["schemaVersion", "id", ...top[name]], name);
233
237
  if (name === "techniques.json") {
234
238
  if (!Array.isArray(value.techniques) || value.techniques.length > 100) add("techniques must contain at most 100 entries.");
@@ -258,6 +262,7 @@ function styleReuseIssues(name, value, expectedId) {
258
262
  }
259
263
  if (name === "captions.json") {
260
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.");
261
266
  fields(f, ["family", "weight", "size", "color", "resourceId"], "Caption font");
262
267
  fields(b, ["color", "padding"], "Caption activeBox");
263
268
  fields(p, ["x", "y"], "Caption position");
@@ -283,9 +288,10 @@ function styleReuseIssues(name, value, expectedId) {
283
288
  }
284
289
  fields(c, ["id", "sourceResourceId", "originPath", "status", "bindings"], "Component");
285
290
  const names = /* @__PURE__ */ new Set();
286
- for (const b of c.bindings) {
287
- fields(b, ["name", "type", "literal", "occurrences", "role"], "Binding");
288
- if (!obj(b) || !id(b.name) || names.has(b.name) || !["string", "number", "boolean"].includes(String(b.type)) || typeof b.literal !== b.type || typeof b.literal === "number" && !Number.isFinite(b.literal) || typeof b.literal === "string" && b.literal.length > 8e3 || !Number.isInteger(b.occurrences) || Number(b.occurrences) < 1 || Number(b.occurrences) > 1e3 || b.role === "clip" && b.type !== "string" || b.role !== void 0 && !["clip", "text", "timing", "layout"].includes(String(b.role))) add("Bindings need unique name, type string|number|boolean, literal of that type, occurrences:1..1000 and optional role clip|text|timing|layout.");
291
+ for (const [index, b] of c.bindings.entries()) {
292
+ const label = `Component ${c.id}, binding ${index + 1}${obj(b) ? " (" + JSON.stringify(b.name) + ")" : ""}`;
293
+ fields(b, ["name", "type", "literal", "occurrences", "role"], label);
294
+ if (!obj(b) || !bindingName(b.name) || names.has(b.name) || !["string", "number", "boolean"].includes(String(b.type)) || typeof b.literal !== b.type || typeof b.literal === "number" && !Number.isFinite(b.literal) || typeof b.literal === "string" && b.literal.length > 8e3 || !Number.isInteger(b.occurrences) || Number(b.occurrences) < 1 || Number(b.occurrences) > 1e3 || ["clip", "directory"].includes(String(b.role)) && b.type !== "string" || b.role !== void 0 && !["clip", "directory", "text", "timing", "layout"].includes(String(b.role))) add(`${label}: use a unique name starting with a letter or number (letters, numbers, _ or -, max 80; camelCase allowed), type string|number|boolean, literal of that type, occurrences:1..1000 and optional role clip|directory|text|timing|layout. Clip and directory bindings require type string.`);
289
295
  if (obj(b)) names.add(b.name);
290
296
  }
291
297
  if (c.status === "parameterized" && !c.bindings.length) add("Parameterized components require explicit bindings.");
@@ -306,12 +312,22 @@ function validateCaptionCues(value) {
306
312
  for (const item of value) {
307
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.");
308
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
+ }
309
324
  }
310
325
  return value;
311
326
  }
312
327
  function captionLayer(preset, cues, width, height, fontDataUrl) {
313
328
  validateStyleReuse("captions.json", preset, preset.id);
314
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.");
315
331
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 16 || height < 16 || width > 8192 || height > 8192) throw new Error("Invalid caption canvas dimensions.");
316
332
  if (fontDataUrl && !/^data:font\/(?:woff2?|ttf|otf);base64,[A-Za-z0-9+/]+=*$/.test(fontDataUrl)) throw new Error("Invalid embedded font.");
317
333
  const data = JSON.stringify({ preset, cues, width, height, fontDataUrl }).replace(/[<>&\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
@@ -323,7 +339,16 @@ window.renderAt=async function(seconds){
323
339
  await fontReady;await document.fonts.ready;el.hidden=true;
324
340
  const cue=data.cues.find(c=>seconds>=c.start&&seconds<c.end);
325
341
  if(!p.enabled||!cue||(p.hideDuringCrossings&&cue.crossing))return {visible:false};
326
- 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;
327
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);
328
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'};}
329
354
  return {visible:true,text:cue.text};
@@ -527,19 +552,19 @@ function recoveryHint(help) {
527
552
  // packages/core/src/tool-preferences.ts
528
553
  var toolLanguages = ["project", "es", "en", "pt", "fr", "de", "it"];
529
554
  function validateToolPreferences(input) {
530
- const obj2 = (value2, keys2) => {
555
+ const obj3 = (value2, keys2) => {
531
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.");
532
557
  return value2;
533
558
  };
534
559
  const choice = (v, values) => {
535
560
  if (!values.includes(v)) throw new Error("Unsupported AI tool preference.");
536
561
  };
537
- const value = obj2(input, ["schemaVersion", "transcription", "images", "narration", "music"]);
562
+ const value = obj3(input, ["schemaVersion", "transcription", "images", "narration", "music"]);
538
563
  if (value.schemaVersion !== 1) throw new Error("Tool preferences schemaVersion must be 1.");
539
564
  for (const key of ["transcription", "images", "narration", "music"]) {
540
565
  if (value[key] === void 0) continue;
541
566
  const fields = { transcription: ["provider", "language"], images: ["provider", "quality", "resolution", "aspectRatio"], narration: ["provider", "language"], music: ["provider", "durationSeconds", "character"] }[key];
542
- const section = obj2(value[key], fields);
567
+ const section = obj3(value[key], fields);
543
568
  if (fields.some((field) => section[field] === void 0)) throw new Error("Incomplete AI tool preferences.");
544
569
  const providers = { transcription: ["editorbrain", "assemblyai"], images: ["editorbrain", "higgsfield", "openai-images"], narration: ["editorbrain", "elevenlabs"], music: ["editorbrain", "suno", "elevenlabs"] }[key];
545
570
  choice(section.provider, providers);
@@ -1621,8 +1646,8 @@ function text3(value, name, max = 200) {
1621
1646
  function validateAudioLoudnessTarget(value) {
1622
1647
  const input = record4(value, "loudness", ["targetIntegratedLufs", "toleranceLu", "maxTruePeakDbtp"]);
1623
1648
  for (const field of ["targetIntegratedLufs", "toleranceLu", "maxTruePeakDbtp"]) {
1624
- const number2 = input[field];
1625
- 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.`);
1626
1651
  }
1627
1652
  return { targetIntegratedLufs: input.targetIntegratedLufs, toleranceLu: input.toleranceLu, maxTruePeakDbtp: input.maxTruePeakDbtp };
1628
1653
  }
@@ -181619,12 +181644,12 @@ var SOCIAL_SAFE_PROFILES = {
181619
181644
  reels: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 },
181620
181645
  shorts: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 }
181621
181646
  };
181622
- function validateVisualReview(value, hash8, duration, width, height) {
181647
+ function validateVisualReview(value, hash9, duration, width, height) {
181623
181648
  const v = value;
181624
181649
  const fail3 = () => {
181625
181650
  throw new Error("Invalid visual profile: use the exact artifact hash, output-clock seconds and output-pixel boxes.");
181626
181651
  };
181627
- 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();
181628
181653
  if (Object.keys(v).some((k) => !["schemaVersion", "artifactSha256", "platform", "holds", "geometry"].includes(k))) fail3();
181629
181654
  if (v.platform !== void 0 && !Object.hasOwn(SOCIAL_SAFE_PROFILES, v.platform)) fail3();
181630
181655
  if (v.holds !== void 0 && (!Array.isArray(v.holds) || v.holds.length > 1e3)) fail3();
@@ -181660,7 +181685,7 @@ function parseReviewTranscript(value) {
181660
181685
  const fail3 = () => {
181661
181686
  throw new Error("Invalid review transcript: use schemaVersion 1, durationMs and up to 200 unique timed phrases. Kept phrases use sample times; removed phrases require source times only.");
181662
181687
  };
181663
- const object13 = (v, keys2) => {
181688
+ const object14 = (v, keys2) => {
181664
181689
  if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys2.includes(k))) fail3();
181665
181690
  return v;
181666
181691
  };
@@ -181668,13 +181693,13 @@ function parseReviewTranscript(value) {
181668
181693
  if (!Number.isSafeInteger(v) || v < 0 || v > 36e6) fail3();
181669
181694
  return v;
181670
181695
  };
181671
- const root = object13(value, ["schemaVersion", "durationMs", "segments"]);
181696
+ const root = object14(value, ["schemaVersion", "durationMs", "segments"]);
181672
181697
  if (root.schemaVersion !== 1 || !Array.isArray(root.segments) || root.segments.length > 200) fail3();
181673
181698
  const durationMs = ms(root.durationMs);
181674
181699
  if (!durationMs) fail3();
181675
181700
  const ids2 = /* @__PURE__ */ new Set();
181676
181701
  const segments = root.segments.map((v) => {
181677
- const s = object13(v, ["id", "text", "state", "startMs", "endMs", "source"]);
181702
+ const s = object14(v, ["id", "text", "state", "startMs", "endMs", "source"]);
181678
181703
  if (typeof s.id !== "string" || !/^[a-zA-Z0-9_-]{1,80}$/.test(s.id) || ids2.has(s.id) || typeof s.text !== "string" || !s.text.trim() || s.text.length > 500 || !["kept", "removed"].includes(s.state)) fail3();
181679
181704
  const id3 = s.id;
181680
181705
  ids2.add(id3);
@@ -181685,7 +181710,7 @@ function parseReviewTranscript(value) {
181685
181710
  if (segment.endMs <= segment.startMs || segment.endMs > durationMs) fail3();
181686
181711
  } else if (s.startMs !== void 0 || s.endMs !== void 0 || !s.source) fail3();
181687
181712
  if (s.source !== void 0) {
181688
- const source2 = object13(s.source, ["assetId", "startMs", "endMs"]);
181713
+ const source2 = object14(s.source, ["assetId", "startMs", "endMs"]);
181689
181714
  if (typeof source2.assetId !== "string" || !/^[a-f0-9]{64}$/.test(source2.assetId)) fail3();
181690
181715
  segment.source = { assetId: source2.assetId, startMs: ms(source2.startMs), endMs: ms(source2.endMs) };
181691
181716
  if (segment.source.endMs <= segment.source.startMs) fail3();
@@ -182526,20 +182551,6 @@ function canonicalFiles(files) {
182526
182551
  return result2;
182527
182552
  }
182528
182553
 
182529
- // packages/cli/src/style-assets.ts
182530
- function styleAssetPath(id3, source2) {
182531
- assertIdentifier(id3);
182532
- if (!/^[a-f0-9]{64}$/.test(source2.assetId)) throw new Error("Invalid asset hash");
182533
- const ext = source2.fileName ? posix.extname(source2.fileName).toLowerCase() : ".bin";
182534
- if (!/^\.[a-z0-9]{1,10}$/.test(ext)) throw new Error("Invalid asset extension");
182535
- return `production-assets/styles/${id3}/${source2.assetId}${ext}`;
182536
- }
182537
-
182538
- // packages/cli/src/style-sync.ts
182539
- import { createHash as createHash3 } from "node:crypto";
182540
- import { lstat as lstat4 } from "node:fs/promises";
182541
- import { posix as posix3 } from "node:path";
182542
-
182543
182554
  // packages/cli/src/io.ts
182544
182555
  import { constants } from "node:fs";
182545
182556
  import { lstat, mkdir, open, readdir, realpath, rename, unlink, link } from "node:fs/promises";
@@ -182556,7 +182567,7 @@ async function checkedPath(root, path, document2 = true) {
182556
182567
  if (document2) safeDocumentPath(path);
182557
182568
  const target = resolve(root, path);
182558
182569
  const rel = relative(root, target);
182559
- if (!rel || rel.startsWith(`..${sep}`) || rel === ".." || resolve(path) === path) throw new Error("Path escapes workspace");
182570
+ if (!rel || rel.startsWith(`..${sep}`) || rel === ".." || resolve(path) === path) throw new Error(`Path escapes workspace: ${JSON.stringify(path)}. Use a workspace-relative path inside ${JSON.stringify(root)}; absolute paths and parent traversal are not accepted. Copy the input into this workspace first.`);
182560
182571
  let cursor = root;
182561
182572
  for (const segment of rel.split(sep)) {
182562
182573
  cursor = join(cursor, segment);
@@ -182655,9 +182666,6 @@ async function readProjectWorkspace(root, projectId) {
182655
182666
  return canonicalFiles(files);
182656
182667
  }
182657
182668
 
182658
- // packages/cli/src/client.ts
182659
- import { setTimeout as delay } from "node:timers/promises";
182660
-
182661
182669
  // packages/cli/src/errors.ts
182662
182670
  var CliError = class extends Error {
182663
182671
  constructor(code, message, hint, retryable = false, details = {}) {
@@ -182677,10 +182685,784 @@ function errorOutput(error) {
182677
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 };
182678
182686
  const message = error instanceof Error ? error.message : "Unknown error";
182679
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." };
182680
182691
  return { error: safe, code: "COMMAND_FAILED", retryable: false, hint: "Read the command help and run editorbrain doctor. Do not retry writes blindly." };
182681
182692
  }
182682
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
+
182683
183464
  // packages/cli/src/client.ts
183465
+ import { setTimeout as delay } from "node:timers/promises";
182684
183466
  var searchErrors = {
182685
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." },
182686
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." },
@@ -182706,6 +183488,10 @@ var searchErrors = {
182706
183488
  studio_preference_conflict: { status: 409, code: "STUDIO_PREFERENCE_CONFLICT", hint: "Reconcile project language, voice, music or media-source preferences before generating." },
182707
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." },
182708
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." },
182709
183495
  studio_queue_full: { status: 429, code: "STUDIO_QUEUE_FULL", hint: "Wait for existing Studio jobs to finish. Do not create replacement quotes." },
182710
183496
  billing_review_required: { status: 409, code: "BILLING_REVIEW_REQUIRED", hint: "A payment needs review. Contact support before starting another paid job." },
182711
183497
  batch_changed: { status: 409, code: "BATCH_CHANGED", hint: "Read batches get before retrying; preserve new changes." },
@@ -182739,6 +183525,14 @@ function safeDiagnosticDetails(body) {
182739
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]);
182740
183526
  if (["workspace", "service"].includes(String(e.scope))) details.scope = String(e.scope);
182741
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
+ }
182742
183536
  return details;
182743
183537
  }
182744
183538
  var ApiError = class extends CliError {
@@ -182867,12 +183661,12 @@ var Client = class {
182867
183661
  return this.request(`/v1/documents/${safeDocumentPath(path).split("/").map(encodeURIComponent).join("/")}`, { method: "PUT", body: { content, expectedRevision } });
182868
183662
  }
182869
183663
  async uploadPreview(path, content, mimeType) {
182870
- const hash8 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
182871
- 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.");
182872
183666
  const sourceHash = new URL(path, this.url).searchParams.get("sourceSha256");
182873
- 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.");
182874
183668
  let plan;
182875
- const params = new URLSearchParams({ sha256: hash8, bytes: String(content.byteLength) });
183669
+ const params = new URLSearchParams({ sha256: hash9, bytes: String(content.byteLength) });
182876
183670
  const projectId = new URL(path, "https://local.invalid").searchParams.get("projectId");
182877
183671
  if (projectId) params.set("projectId", projectId);
182878
183672
  try {
@@ -182884,7 +183678,7 @@ var Client = class {
182884
183678
  if (typeof plan.allowed !== "boolean" || !Number.isSafeInteger(plan.additionalBytes)) throw new Error("Invalid preview preflight response.");
182885
183679
  if (plan.existingAsset) {
182886
183680
  const asset = plan.existingAsset;
182887
- 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.");
182888
183682
  return new Response(JSON.stringify({ ...asset, reused: true }), { headers: { "Content-Type": "application/json" } });
182889
183683
  }
182890
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.");
@@ -183041,16 +183835,17 @@ ${conflicts.join("\n")}`, "Run pull --dry-run and reconcile the reported paths."
183041
183835
  }
183042
183836
 
183043
183837
  // packages/cli/src/style-project.ts
183044
- import { createHash } from "node:crypto";
183045
- import { readdir as readdir2 } 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";
183046
183841
  import { posix as posix2 } from "node:path";
183047
183842
 
183048
183843
  // packages/cli/src/review-files.ts
183049
- import { constants as constants2 } from "node:fs";
183050
- 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";
183051
183846
  var REVIEW_MEDIA_BYTES = 24 * 1024 * 1024;
183052
183847
  async function readReviewFile(path, maxBytes) {
183053
- 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);
183054
183849
  try {
183055
183850
  const before = await handle.stat();
183056
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.");
@@ -183070,27 +183865,61 @@ async function readReviewFile(path, maxBytes) {
183070
183865
  }
183071
183866
 
183072
183867
  // packages/cli/src/style-project.ts
183073
- var media = /\.(png|jpe?g|webp|mp4|mov|webm|wav|mp3|m4a|ogg|woff2?|ttf|otf|html|js|mjs)$/i;
183074
- var digest2 = (b) => createHash("sha256").update(b).digest("hex");
183075
- 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";
183076
- async function buildStyleFromProject(root, id3, projectId, name) {
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");
183870
+ var object7 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
183871
+ function generationReceipt(value) {
183872
+ if (!object7(value)) return;
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;
183874
+ }
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";
183876
+ async function videoEvidenceHash(path, expectedSize) {
183877
+ const handle = await open7(path, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
183878
+ try {
183879
+ const before = await handle.stat();
183880
+ if (!before.isFile() || before.size !== expectedSize) throw new Error("Video changed before hashing");
183881
+ const hash9 = createHash4("sha256"), chunk = Buffer.alloc(1024 * 1024);
183882
+ let offset = 0;
183883
+ while (offset < before.size) {
183884
+ const { bytesRead } = await handle.read(chunk, 0, Math.min(chunk.length, before.size - offset), offset);
183885
+ if (!bytesRead) throw new Error("Video changed while hashing");
183886
+ hash9.update(chunk.subarray(0, bytesRead));
183887
+ offset += bytesRead;
183888
+ }
183889
+ const after = await handle.stat();
183890
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new Error("Video changed while hashing");
183891
+ return hash9.digest("hex");
183892
+ } finally {
183893
+ await handle.close();
183894
+ }
183895
+ }
183896
+ async function buildStyleFromProject(root, id3, projectId, name, scenePath) {
183077
183897
  assertIdentifier(projectId);
183078
183898
  const prefix = `videos/${projectId}`, projectPath = `${prefix}/project.json`;
183079
183899
  const raw = await readText(root, projectPath);
183080
183900
  const v = validateDocument(projectPath, raw);
183081
183901
  if (!v.valid) throw new Error(v.issues.map((x) => x.message).join("\n"));
183082
183902
  const project = JSON.parse(raw), files = createStyle({ id: id3, name }), base = `.editorbrain/styles/${id3}`;
183903
+ const notes = /* @__PURE__ */ new Map();
183083
183904
  const warnings = [], candidates = /* @__PURE__ */ new Set(), jsonFiles = [], receipts = [];
183084
183905
  let scanned = 0;
183906
+ const roots = [prefix, `.editorbrain-local/${projectId}`], scannedRoots = [];
183907
+ const allowed = (path) => !path.startsWith(".editorbrain/") && (!path.startsWith("videos/") || path.startsWith(prefix + "/")) && (!path.startsWith(".editorbrain-local/") || path.startsWith(roots[1] + "/"));
183085
183908
  async function walk(directory, depth) {
183086
- if (depth > 4) {
183909
+ if (depth > 8) {
183087
183910
  warnings.push(`Directory depth limit: ${directory}`);
183088
183911
  return;
183089
183912
  }
183090
- for (const entry of (await readdir2(await checkedPath(root, directory, false), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
183091
- if (++scanned > 500) throw new Error("Project capture exceeds 500 entries; select a smaller project or an explicit resource manifest.");
183092
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
183913
+ for (const entry of (await readdir5(await checkedPath(root, directory, false), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
183914
+ if (++scanned > 2e3) throw new Error("Project capture exceeds 2000 entries; select a smaller project or an explicit resource manifest.");
183915
+ if (entry.name.startsWith(".") || ["node_modules", "vendor", "qa", "frames", "source", "scene-sources", "render-report-history"].includes(entry.name)) continue;
183093
183916
  const path = `${directory}/${entry.name}`;
183917
+ try {
183918
+ safeStyleResourcePath(path);
183919
+ } catch {
183920
+ warnings.push(`Skipped private or unsafe path: ${path}`);
183921
+ continue;
183922
+ }
183094
183923
  if (entry.isSymbolicLink()) {
183095
183924
  warnings.push(`Skipped symlink: ${path}`);
183096
183925
  continue;
@@ -183100,112 +183929,230 @@ async function buildStyleFromProject(root, id3, projectId, name) {
183100
183929
  continue;
183101
183930
  }
183102
183931
  if (!entry.isFile()) continue;
183932
+ if (["direction.md", "review.md"].includes(entry.name)) notes.set(entry.name, [...notes.get(entry.name) ?? [], path]);
183103
183933
  if (media.test(path)) candidates.add(path);
183104
- if (/(?:sources|media|resources|production-plan|narrative-beats|beats|takeover-[^/]+)\.json$/.test(path)) {
183934
+ if (path.endsWith(".json")) {
183105
183935
  try {
183106
183936
  const bytes = await readReviewFile(await checkedPath(root, path, false), 128 * 1024), value = JSON.parse(bytes.toString());
183107
- jsonFiles.push({ path, value });
183108
- if (/takeover-/.test(path)) receipts.push({ path, sha256: digest2(bytes), ...typeof value.model === "string" && /^[a-zA-Z0-9 ._/-]{1,100}$/.test(value.model) ? { model: value.model } : {} });
183937
+ if (object7(value) || Array.isArray(value)) jsonFiles.push({ path, value });
183938
+ const receipt = generationReceipt(value);
183939
+ if (receipt) receipts.push({ path, sha256: digest2(bytes), ...typeof receipt.model === "string" && /^[a-zA-Z0-9 ._/-]{1,100}$/.test(receipt.model) ? { model: receipt.model } : {} });
183109
183940
  } catch {
183110
183941
  warnings.push(`Unparsed or oversized manifest: ${path}`);
183111
183942
  }
183112
183943
  }
183113
183944
  }
183114
183945
  }
183115
- await walk(prefix, 0);
183116
- function discover(value, parent, depth = 0) {
183946
+ for (const directory of roots) {
183947
+ try {
183948
+ const info = await lstat5(await checkedPath(root, directory, false));
183949
+ if (!info.isDirectory()) throw new Error(`Project capture root is not a directory: ${directory}`);
183950
+ } catch (error) {
183951
+ if (error.code === "ENOENT") continue;
183952
+ throw error;
183953
+ }
183954
+ await walk(directory, 0);
183955
+ scannedRoots.push(directory);
183956
+ }
183957
+ async function discover(value, parent, depth = 0) {
183117
183958
  if (depth > 12) return;
183118
183959
  if (Array.isArray(value)) {
183119
- for (const item of value.slice(0, 500)) discover(item, parent, depth + 1);
183960
+ for (const item of value.slice(0, 500)) await discover(item, parent, depth + 1);
183120
183961
  return;
183121
183962
  }
183122
183963
  if (value && typeof value === "object") for (const [key, item] of Object.entries(value)) {
183123
183964
  if (["path", "file", "localPath", "outputPath", "src"].includes(key) && typeof item === "string" && media.test(item)) {
183124
- for (const candidate of [item, posix2.join(posix2.dirname(parent), item)]) try {
183965
+ const paths2 = [];
183966
+ if (item.startsWith("videos/") || item.startsWith(".editorbrain-local/") || item.startsWith("production-assets/")) paths2.push(item);
183967
+ else for (let directory = posix2.dirname(parent); allowed(directory + "/") && (directory === prefix || directory.startsWith(prefix + "/") || directory === roots[1] || directory.startsWith(roots[1] + "/")); directory = posix2.dirname(directory)) paths2.push(posix2.join(directory, item));
183968
+ const existing = /* @__PURE__ */ new Set();
183969
+ for (const candidate of paths2) try {
183125
183970
  safeStyleResourcePath(candidate);
183126
- candidates.add(candidate);
183971
+ if (!allowed(candidate)) continue;
183972
+ const info = await lstat5(await checkedPath(root, candidate, false));
183973
+ if (info.isFile()) existing.add(candidate);
183127
183974
  } catch {
183128
- warnings.push(`Ignored unsafe resource locator in ${parent}`);
183129
183975
  }
183130
- } else discover(item, parent, depth + 1);
183976
+ if (existing.size === 1) candidates.add([...existing][0]);
183977
+ else warnings.push(`${existing.size ? "Ambiguous" : "Missing or unsafe"} resource locator in ${parent}; declare a workspace-relative path.`);
183978
+ } else await discover(item, parent, depth + 1);
183131
183979
  }
183132
183980
  }
183133
- for (const entry of jsonFiles) discover(entry.value, entry.path);
183134
- for (const path of [...candidates].filter((p) => p.endsWith(".html"))) {
183135
- try {
183136
- const html = (await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024)).toString();
183137
- for (const m of html.matchAll(/(?:src\s*=\s*["']|url\(["']?)([^"')\s>]+)/g)) {
183138
- const child = posix2.join(posix2.dirname(path), m[1]);
183139
- try {
183140
- safeStyleResourcePath(child);
183141
- if (media.test(child)) candidates.add(child);
183142
- } catch {
183143
- }
183981
+ for (const entry of jsonFiles) await discover(entry.value, entry.path);
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));
183144
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);
183145
184009
  } catch {
183146
- warnings.push(`Could not inspect scene dependencies: ${path}`);
184010
+ }
184011
+ return found.length === 1 ? found[0] : void 0;
184012
+ }
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
+ }
183147
184021
  }
183148
184022
  }
183149
- if (candidates.size > 200) throw new Error("More than 200 candidate resources; curate this project before capturing it.");
183150
- const resources = [], examples = [], hashes = /* @__PURE__ */ new Map();
183151
- let bytesRead = 0;
183152
- for (const path of [...candidates].sort()) try {
183153
- safeStyleResourcePath(path);
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) => {
184032
+ try {
184033
+ return { path, size: (await lstat5(await checkedPath(root, path, false))).size };
184034
+ } catch {
184035
+ return { path, size: Number.MAX_SAFE_INTEGER };
184036
+ }
184037
+ }));
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 {
184040
+ if (size === Number.MAX_SAFE_INTEGER) {
184041
+ warnings.push(`Resource missing or unsafe: ${path}`);
184042
+ continue;
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
+ }
184060
+ if (bytesRead + size > 512 * 1024 * 1024) {
184061
+ warnings.push(`Capture byte budget reached; omitted ${path}. Declare it explicitly if needed.`);
184062
+ continue;
184063
+ }
183154
184064
  const bytes = await readReviewFile(await checkedPath(root, path, false), 90 * 1024 * 1024);
183155
184065
  bytesRead += bytes.length;
183156
- if (bytesRead > 512 * 1024 * 1024) throw new Error("Project capture exceeds 512 MiB; use lightweight review assets.");
183157
- const hash8 = digest2(bytes), rid = `resource-${resources.length + 1}`;
183158
- hashes.set(hash8, rid);
183159
- 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 } });
183160
- if (/(?:^|\/)renders\//.test(path) && kind(path) === "video") examples.push({ id: `render-${examples.length + 1}`, projectId, resourceId: rid, sha256: hash8, reviewStatus: "unreviewed" });
184066
+ const hash9 = digest2(bytes), existing = hashes.get(hash9);
184067
+ if (existing) {
184068
+ duplicatePaths.push({ path, resourceId: existing });
184069
+ continue;
184070
+ }
184071
+ if (resources.length >= 200) {
184072
+ warnings.push(`Portable manifest limit (200 unique resources): omitted ${path}; curate explicit dependencies.`);
184073
+ continue;
184074
+ }
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 } });
183161
184078
  } catch (error) {
183162
- if (error.message.startsWith("Project capture exceeds")) throw error;
183163
- warnings.push(`Resource unavailable or unsupported: ${path}`);
184079
+ warnings.push(`Resource unavailable or unsupported: ${path}: ${error.message}`);
183164
184080
  }
183165
184081
  const beats = jsonFiles.flatMap(({ value }) => Array.isArray(value.beats) ? value.beats : Array.isArray(value.uses) ? value.uses : []);
183166
184082
  for (const [i, b] of beats.entries()) {
183167
- const t = b.timeline ?? b, start3 = t.startSeconds, end3 = t.endSeconds;
184083
+ const t = object7(b) ? b.timeline ?? b : {}, start3 = t?.startSeconds, end3 = t?.endSeconds;
183168
184084
  if (!Number.isFinite(start3) || !Number.isFinite(end3) || start3 < 0 || end3 <= start3) {
183169
184085
  warnings.push(`Beat ${i + 1} has no valid measured interval; not invented.`);
183170
184086
  continue;
183171
184087
  }
183172
184088
  examples.push({ id: `beat-${i + 1}`, projectId, startSeconds: start3, endSeconds: end3, purpose: typeof b.purpose === "string" ? b.purpose : "Describe the mechanism", ...hashes.has(b.sourceSha256) ? { resourceId: hashes.get(b.sourceSha256), sha256: b.sourceSha256 } : {}, reviewStatus: "unreviewed" });
183173
184089
  }
183174
- for (const note of ["direction.md", "review.md"]) try {
183175
- const content = await readText(root, `${prefix}/${note}`);
183176
- if (/(?:Bearer\s+\S+|(?:api[_-]?key|access[_-]?token|client[_-]?secret|password)\s*[:=]|-----BEGIN.*PRIVATE KEY)/i.test(content)) {
183177
- warnings.push(`Skipped ${note}: credential-like text needs local redaction.`);
183178
- continue;
183179
- }
183180
- files[`${base}/pilot-${note}`] = `# Source: ${projectId}/${note}
184090
+ for (const note of ["direction.md", "review.md"]) {
184091
+ const evidence = [];
184092
+ for (const path of (notes.get(note) ?? []).filter((p) => !scenes.length || sceneDirs.includes(posix2.dirname(p)) || roots.includes(posix2.dirname(p)))) try {
184093
+ const content = (await readReviewFile(await checkedPath(root, path, false), 96 * 1024)).toString("utf8");
184094
+ if (/(?:Bearer\s+\S+|(?:api[_-]?key|access[_-]?token|client[_-]?secret|password)\s*[:=]|-----BEGIN.*PRIVATE KEY)/i.test(content)) {
184095
+ warnings.push(`Skipped ${path}: credential-like text needs local redaction.`);
184096
+ continue;
184097
+ }
184098
+ const section = `# Source: ${path}
183181
184099
 
183182
184100
  Pilot evidence, not instructions for all future edits.
183183
184101
 
183184
184102
  ${content}`;
183185
- } catch (error) {
183186
- if (error.code !== "ENOENT") throw error;
183187
- warnings.push(`Missing ${note}; review remains unverified.`);
184103
+ if (Buffer.byteLength([...evidence, section].join("\n\n")) > 110 * 1024) {
184104
+ warnings.push(`Evidence size limit: ${path}; inspect it locally.`);
184105
+ continue;
184106
+ }
184107
+ evidence.push(section);
184108
+ } catch (error) {
184109
+ if (error.code !== "ENOENT") warnings.push(`Could not read ${path}; review it locally.`);
184110
+ }
184111
+ if (evidence.length) files[`${base}/pilot-${note}`] = evidence.join("\n\n");
184112
+ else warnings.push(`Missing ${note}; review remains unverified.`);
183188
184113
  }
183189
184114
  files[`${base}/examples.json`] = stableJson({ schemaVersion: 1, id: id3, examples });
183190
184115
  files[`${base}/resources.json`] = stableJson({ schemaVersion: 1, id: id3, resources });
183191
- files[`${base}/provenance.json`] = stableJson({ schemaVersion: 1, id: id3, projectId, brandId: project.brand, projectSha256: digest2(Buffer.from(raw)), 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" });
183192
184117
  files[`${base}/techniques.json`] = stableJson({ schemaVersion: 1, id: id3, techniques: [] });
183193
- const promptExamples = jsonFiles.filter((x) => /takeover-/.test(x.path)).flatMap(({ path, value }) => {
183194
- const prompt = typeof value.prompt === "string" ? value.prompt : typeof value.input?.prompt === "string" ? value.input.prompt : void 0;
183195
- if (!prompt || prompt.length > 8e3 || /(?:https?:\/\/|Bearer\s|api[_-]?key|access[_-]?token|client[_-]?secret|password|-----BEGIN)/i.test(prompt)) {
183196
- if (prompt) warnings.push(`Prompt omitted from ${path}: review it locally before saving.`);
183197
- return [];
184118
+ function receiptEntries(value, depth = 0) {
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));
184121
+ return [value, ...Object.values(value).slice(0, 100).flatMap((child) => receiptEntries(child, depth + 1))];
184122
+ }
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;
183198
184132
  }
183199
- return [{ source: path, prompt, model: typeof value.model === "string" ? value.model : void 0, status: "pilot_example_not_template" }];
183200
- });
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);
184142
+ while (Buffer.byteLength(stableJson({ schemaVersion: 1, id: id3, examples: promptExamples })) > 110 * 1024) {
184143
+ promptExamples.pop();
184144
+ if (!warnings.includes("Prompt example budget reached; remaining prompts need local review.")) warnings.push("Prompt example budget reached; remaining prompts need local review.");
184145
+ }
183201
184146
  if (promptExamples.length) files[`${base}/media-examples.json`] = stableJson({ schemaVersion: 1, id: id3, examples: promptExamples });
183202
184147
  files[`${base}/media-style.json`] = stableJson({ schemaVersion: 1, id: id3, status: "draft", referenceOrder: [], promptTemplate: "{personajes}. {escena}. Paleta: {paleta}.", variables: ["personajes", "escena", "paleta"], reviewBeforeAnimation: [] });
183203
- for (const name2 of ["captions.json", "media-style.json"]) try {
183204
- const parsed = JSON.parse(await readText(root, `${prefix}/${name2}`));
184148
+ for (const name2 of ["captions.json", "media-style.json"]) for (const directory of roots) try {
184149
+ const parsed = JSON.parse((await readReviewFile(await checkedPath(root, `${directory}/${name2}`, false), 128 * 1024)).toString());
183205
184150
  parsed.id = id3;
183206
184151
  const content = stableJson(parsed), validation = validateDocument(`${base}/${name2}`, content);
183207
- if (validation.valid) files[`${base}/${name2}`] = content;
183208
- else warnings.push(`Invalid ${name2} in pilot; not copied. Complete its typed contract.`);
184152
+ if (validation.valid) {
184153
+ files[`${base}/${name2}`] = content;
184154
+ break;
184155
+ } else warnings.push(`Invalid ${name2} in pilot; not copied. Complete its typed contract.`);
183209
184156
  } catch (error) {
183210
184157
  if (error.code !== "ENOENT") warnings.push(`Could not capture ${name2}; complete it explicitly.`);
183211
184158
  }
@@ -183214,71 +184161,20 @@ ${content}`;
183214
184161
 
183215
184162
  Read pilot-direction.md and pilot-review.md when present. Complete: what to preserve; what to adapt; when not to use; verification for each technique. Confirm candidate resources; hashes prove bytes, not whether the scene uses them. Receipts are recorded by hash without copying provider secrets or temporary URLs.
183216
184163
  `;
184164
+ if (!resources.length) warnings.push(`No resources captured in ${scannedRoots.join(", ")}. Inspect project paths or declare resources explicitly; this is not a complete saved style.`);
183217
184165
  warnings.push("Resources are candidates, not a certified dependency graph. Dynamic JS imports/URLs need explicit review. Media recipe is a draft; no model, timing or human approval inferred.");
183218
184166
  for (const [path, content] of Object.entries(files)) {
183219
184167
  const result2 = validateDocument(path, content);
183220
184168
  if (!result2.valid) throw new Error(result2.issues.map((x) => `${path}: ${x.message}`).join("\n"));
183221
184169
  }
183222
- return { files, warnings };
183223
- }
183224
-
183225
- // packages/cli/src/style-authoring.ts
183226
- import { createHash as createHash2 } from "node:crypto";
183227
- import { constants as constants4 } from "node:fs";
183228
- import { lstat as lstat3, mkdir as mkdir2, open as open4, readdir as readdir3, rmdir, unlink as unlink3 } from "node:fs/promises";
183229
- import { dirname as dirname2 } from "node:path";
183230
-
183231
- // packages/cli/src/workspace-lock.ts
183232
- import { constants as constants3 } from "node:fs";
183233
- import { lstat as lstat2, open as open3, rename as rename2, unlink as unlink2 } from "node:fs/promises";
183234
- import { hostname } from "node:os";
183235
- import { randomUUID as randomUUID2 } from "node:crypto";
183236
- var LOCK_PATH = ".editorbrain-operation.lock";
183237
- async function withWorkspaceLock(root, operation, options = {}) {
183238
- const legacyLock = await checkedPath(root, ".editorharness-operation.lock", false);
183239
- let legacy;
183240
- try {
183241
- legacy = await open3(legacyLock, constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW, 384);
183242
- } catch (error) {
183243
- if (error.code === "EEXIST") throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation to finish.");
183244
- throw error;
183245
- }
183246
- try {
183247
- const path = await checkedPath(root, LOCK_PATH, false);
183248
- let handle;
183249
- try {
183250
- handle = await open3(path, constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW, 384);
183251
- } catch (error) {
183252
- if (error.code !== "EEXIST") throw error;
183253
- 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.");
183254
- }
183255
- const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID2(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
183256
- try {
183257
- await handle.writeFile(owner);
183258
- await handle.close();
183259
- const oldRoot = await checkedPath(root, ".editorharness", false);
183260
- const newRoot = await checkedPath(root, ".editorbrain", false);
183261
- const exists3 = async (path2) => lstat2(path2).then(() => true, (error) => {
183262
- if (error.code === "ENOENT") return false;
183263
- throw error;
183264
- });
183265
- if (options.migrateLegacy !== false && await exists3(oldRoot)) {
183266
- 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.");
183267
- await rename2(oldRoot, newRoot);
183268
- }
183269
- return await operation();
183270
- } finally {
183271
- await handle.close().catch(() => {
183272
- });
183273
- if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
183274
- }
183275
- } finally {
183276
- await legacy.close();
183277
- await unlink2(legacyLock);
183278
- }
184170
+ return { files, warnings: [...new Set(warnings)] };
183279
184171
  }
183280
184172
 
183281
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";
183282
184178
  function styleId(id3) {
183283
184179
  try {
183284
184180
  return assertIdentifier(id3);
@@ -183288,7 +184184,7 @@ function styleId(id3) {
183288
184184
  }
183289
184185
  async function exists(path) {
183290
184186
  try {
183291
- await lstat3(path);
184187
+ await lstat6(path);
183292
184188
  return true;
183293
184189
  } catch (error) {
183294
184190
  if (error.code === "ENOENT") return false;
@@ -183317,12 +184213,12 @@ async function makeDirectories(root, path, created) {
183317
184213
  const relative2 = segments.slice(0, i).join("/");
183318
184214
  const target = await checkedPath(root, relative2, false);
183319
184215
  try {
183320
- await mkdir2(target);
183321
- const info = await lstat3(target);
184216
+ await mkdir4(target);
184217
+ const info = await lstat6(target);
183322
184218
  created.push({ path: relative2, dev: info.dev, ino: info.ino });
183323
184219
  } catch (error) {
183324
184220
  if (error.code !== "EEXIST") throw error;
183325
- if (!(await lstat3(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}`);
183326
184222
  }
183327
184223
  }
183328
184224
  }
@@ -183330,21 +184226,22 @@ async function cleanCreated(root, paths2, directory) {
183330
184226
  for (const item of [...paths2].reverse()) {
183331
184227
  try {
183332
184228
  const target = await checkedPath(root, item.path, false);
183333
- const info = await lstat3(target);
184229
+ const info = await lstat6(target);
183334
184230
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
183335
184231
  if (directory) await rmdir(target);
183336
- else await unlink3(target);
184232
+ else await unlink4(target);
183337
184233
  } catch {
183338
184234
  }
183339
184235
  }
183340
184236
  }
183341
184237
  async function createLocalStyle(options) {
183342
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.");
183343
184240
  if (options.name !== void 0 && (!options.name.trim() || options.name.length > 200 || /[\x00-\x1f\x7f]/.test(options.name))) {
183344
184241
  throw new CliError("INVALID_ARGUMENT", "--name must contain 1\u2013200 characters without control characters.", "Use a short, descriptive style name.");
183345
184242
  }
183346
184243
  const root = await ensureRoot(options.directory, true);
183347
- 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;
183348
184245
  const files = seeded?.files ?? createStyle({ id: id3, name: options.name });
183349
184246
  await preflightCreate(root, id3, files);
183350
184247
  return withWorkspaceLock(root, async () => {
@@ -183353,9 +184250,9 @@ async function createLocalStyle(options) {
183353
184250
  const createdDirectories = [];
183354
184251
  try {
183355
184252
  for (const [path, content] of Object.entries(files)) {
183356
- await makeDirectories(root, dirname2(path), createdDirectories);
184253
+ await makeDirectories(root, dirname5(path), createdDirectories);
183357
184254
  const target = await checkedPath(root, path);
183358
- const handle = await open4(target, constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | constants4.O_NOFOLLOW, 420);
184255
+ const handle = await open8(target, constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL | constants8.O_NOFOLLOW, 420);
183359
184256
  try {
183360
184257
  const info = await handle.stat();
183361
184258
  createdFiles.push({ path, dev: info.dev, ino: info.ino });
@@ -183389,12 +184286,12 @@ async function readStyle(root, id3) {
183389
184286
  try {
183390
184287
  const target = await checkedPath(root, path, false);
183391
184288
  if (!await exists(target)) continue;
183392
- if (!(await lstat3(target)).isDirectory()) {
184289
+ if (!(await lstat6(target)).isDirectory()) {
183393
184290
  issues.push({ path, message: "Style path is not a directory." });
183394
184291
  continue;
183395
184292
  }
183396
184293
  directories.push(path);
183397
- const entries = await readdir3(target, { withFileTypes: true });
184294
+ const entries = await readdir6(target, { withFileTypes: true });
183398
184295
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
183399
184296
  if (!/\.(json|md)$/.test(entry.name)) continue;
183400
184297
  const document2 = `${path}/${entry.name}`;
@@ -183418,19 +184315,19 @@ async function readStyle(root, id3) {
183418
184315
  async function checkLocalResource(root, path, expected) {
183419
184316
  safeStyleResourcePath(path);
183420
184317
  const target = await checkedPath(root, path, false);
183421
- const handle = await open4(target, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
184318
+ const handle = await open8(target, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
183422
184319
  try {
183423
184320
  const before = await handle.stat();
183424
184321
  if (!before.isFile()) throw new Error("Resource is not a regular file.");
183425
184322
  if (!expected) return {};
183426
- const hash8 = createHash2("sha256");
183427
- 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);
183428
184325
  const after = await handle.stat();
183429
- const current2 = await lstat3(await checkedPath(root, path, false));
184326
+ const current2 = await lstat6(await checkedPath(root, path, false));
183430
184327
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
183431
184328
  throw new Error("Resource changed while its hash was being checked; check it again.");
183432
184329
  }
183433
- return { actualSha256: hash8.digest("hex") };
184330
+ return { actualSha256: hash9.digest("hex") };
183434
184331
  } finally {
183435
184332
  await handle.close();
183436
184333
  }
@@ -183513,8 +184410,8 @@ async function checkLocalStyle(options) {
183513
184410
 
183514
184411
  // packages/cli/src/style-sync.ts
183515
184412
  var MAX = 90 * 1024 * 1024;
183516
- var digest3 = (bytes) => createHash3("sha256").update(bytes).digest("hex");
183517
- 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" };
183518
184415
  function styleResourceWarnings(files) {
183519
184416
  const warnings = [];
183520
184417
  for (const [path, content] of Object.entries(files)) if (/^\.editorbrain\/styles\/[^/]+\/resources.json$/.test(path)) {
@@ -183549,7 +184446,7 @@ async function boundedStyleDownload(response) {
183549
184446
  async function requireCurrentLayout(root) {
183550
184447
  let legacy = false;
183551
184448
  try {
183552
- await lstat4(await checkedPath(root, ".editorharness", false));
184449
+ await lstat7(await checkedPath(root, ".editorharness", false));
183553
184450
  legacy = true;
183554
184451
  } catch (error) {
183555
184452
  if (error.code !== "ENOENT") throw error;
@@ -183563,28 +184460,33 @@ async function pushStyle(client, directory, id3, options = {}) {
183563
184460
  await requireCurrentLayout(root);
183564
184461
  const me = await client.me();
183565
184462
  await loadSyncState(root, client.url, me.workspaceId);
183566
- const access = await client.request("/v1/team/access");
184463
+ const access = await client.request("/v1/team");
184464
+ if (typeof access.restricted !== "boolean") throw new CliError("INVALID_RESPONSE", "Team permissions are missing.", "Check the API endpoint; no style resources were uploaded.");
183567
184465
  if (access.restricted) throw new CliError("TEAM_SCOPE_DENIED", "Shared styles are managed by the workspace owner.", "Ask the owner to save this style; do not upload its files with another identity.");
183568
184466
  const check = await checkLocalStyle({ directory: root, id: id3 });
183569
184467
  if (!check.valid) throw new CliError("INVALID_STYLE", "Style validation failed.", "Run styles check and correct the reported files.", false, { issues: check.issues });
183570
184468
  const { files } = await readStyle(root, id3), resourcePath = `.editorbrain/styles/${id3}/resources.json`, initial = { ...files };
183571
184469
  const manifest = files[resourcePath] ? JSON.parse(files[resourcePath]) : { schemaVersion: 1, id: id3, resources: [] };
184470
+ const skippedResources = [];
183572
184471
  const uploads = [];
183573
184472
  if (options.withResources) for (const resource of manifest.resources) {
183574
184473
  if (resource.source.type === "requirement") continue;
183575
184474
  if (resource.source.type === "asset") continue;
183576
184475
  const path = resource.source.path, mime = types[posix3.extname(path).toLowerCase()];
183577
- if (!mime) throw new Error(`Unsupported style resource type: ${path}`);
183578
- const bytes = await readReviewFile(await checkedPath(root, path, false), MAX), hash8 = digest3(bytes);
183579
- 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}`);
183580
184482
  const ext = posix3.extname(path).toLowerCase(), name = "asset-" + posix3.basename(path, ext).replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 80) + ext;
183581
- uploads.push({ resource, path, hash: hash8, mime, name });
183582
- 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 };
183583
184485
  }
183584
184486
  if (options.withResources && files[resourcePath]) files[resourcePath] = stableJson(manifest);
183585
184487
  const preview = await pushWorkspace(client, root, files, { dryRun: true });
183586
184488
  if (preview.conflicts?.length) throw new CliError("SYNC_CONFLICT", "Style changed remotely.", "Reconcile before uploading resources.", false, { conflicts: preview.conflicts });
183587
- 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 };
183588
184490
  const verified = [];
183589
184491
  for (const upload of uploads) {
183590
184492
  const bytes = await readReviewFile(await checkedPath(root, upload.path, false), MAX);
@@ -183614,7 +184516,7 @@ async function pushStyle(client, directory, id3, options = {}) {
183614
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.");
183615
184517
  const result2 = await pushWorkspace(client, root, files);
183616
184518
  if (options.withResources && files[resourcePath] !== initial[resourcePath]) await atomicWrite(root, resourcePath, files[resourcePath]);
183617
- 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 };
183618
184520
  }, { migrateLegacy: false });
183619
184521
  }
183620
184522
  async function pullStyle(client, directory, id3, options = {}) {
@@ -183667,10 +184569,10 @@ async function pullStyle(client, directory, id3, options = {}) {
183667
184569
  }
183668
184570
 
183669
184571
  // packages/cli/src/style-operations.ts
183670
- import { createHash as createHash4 } from "node:crypto";
183671
- import { unlink as unlink4 } 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";
183672
184574
  import { posix as posix4 } from "node:path";
183673
- var hash4 = (bytes) => createHash4("sha256").update(bytes).digest("hex");
184575
+ var hash5 = (bytes) => createHash7("sha256").update(bytes).digest("hex");
183674
184576
  var readJson = async (root, path) => JSON.parse((await readReviewFile(await checkedPath(root, path, false), 1024 * 1024)).toString("utf8"));
183675
184577
  var jsonLiteral = (value) => JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
183676
184578
  async function localStyle(root, id3) {
@@ -183701,7 +184603,7 @@ function bindingSpans(code, bindings) {
183701
184603
  let index = 0, count = 0;
183702
184604
  while ((index = code.indexOf(literal, index)) !== -1) {
183703
184605
  if (b.type === "string" || !/[\w.$-]/.test(code[index - 1] ?? "") && !/[\w.]/.test(code[index + literal.length] ?? "")) {
183704
- if (!scripts.some((s) => index >= s.start && index + literal.length <= s.end)) throw new Error("Bindings must target JSON literals inside script blocks, never HTML attributes or markup.");
184606
+ if (!scripts.some((s) => index >= s.start && index + literal.length <= s.end)) throw new Error(`Binding ${b.name}: must target JSON literals inside script blocks, never HTML attributes or markup.`);
183705
184607
  spans.push({ start: index, end: index + literal.length, binding: b });
183706
184608
  count++;
183707
184609
  }
@@ -183710,12 +184612,16 @@ function bindingSpans(code, bindings) {
183710
184612
  if (count !== b.occurrences) throw new Error(`Binding ${b.name}: expected ${b.occurrences} exact JSON literal occurrences; found ${count}. Use a dedicated configuration object in the scene.`);
183711
184613
  }
183712
184614
  spans.sort((a, b) => a.start - b.start);
183713
- for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw new Error("Overlapping bindings; use distinct configuration literals.");
184615
+ for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw new Error(`Overlapping bindings ${spans[i - 1].binding.name} and ${spans[i].binding.name}; use distinct configuration literals.`);
183714
184616
  return spans;
183715
184617
  }
183716
184618
  async function extractComponent(directory, id3, componentId, scene, bindingsFile) {
183717
184619
  assertIdentifier(componentId);
183718
- safeStyleResourcePath(scene);
184620
+ try {
184621
+ safeStyleResourcePath(scene);
184622
+ } catch (error) {
184623
+ throw new Error(`Scene ${JSON.stringify(scene)}: ${error.message}. Copy the input inside ${JSON.stringify(directory)} and pass its workspace-relative path.`);
184624
+ }
183719
184625
  if (!/\.html$/.test(scene)) throw new Error("Scene must be a local HTML file.");
183720
184626
  const root = await ensureRoot(directory);
183721
184627
  return withWorkspaceLock(root, async () => {
@@ -183731,7 +184637,7 @@ async function extractComponent(directory, id3, componentId, scene, bindingsFile
183731
184637
  bindingSpans(code, bindings);
183732
184638
  const manifest = JSON.parse(files[base + "resources.json"] ?? stableJson({ schemaVersion: 1, id: id3, resources: [] }));
183733
184639
  if (manifest.resources.some((r) => r.id === resourceId)) throw new Error("Component resource ID already exists.");
183734
- 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`;
183735
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 } });
183736
184642
  const style = JSON.parse(files[base + "style.json"]);
183737
184643
  style.components = [...(style.components ?? []).filter((c) => c.id !== componentId), { id: componentId, status: bindings.length ? "implemented" : "concept" }];
@@ -183747,7 +184653,7 @@ async function extractComponent(directory, id3, componentId, scene, bindingsFile
183747
184653
  if (error.code !== "ENOENT") throw error;
183748
184654
  }
183749
184655
  if (previousSource) {
183750
- 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.");
183751
184657
  } else await atomicWrite(root, destination, bytes, { document: false, overwrite: false });
183752
184658
  for (const path of Object.keys(changes)) {
183753
184659
  let current2;
@@ -183768,7 +184674,7 @@ async function extractComponent(directory, id3, componentId, scene, bindingsFile
183768
184674
  for (const path of written.reverse()) try {
183769
184675
  if (await readText(root, path) === changes[path]) {
183770
184676
  if (files[path] !== void 0) await atomicWrite(root, path, files[path]);
183771
- else await unlink4(await checkedPath(root, path));
184677
+ else await unlink5(await checkedPath(root, path));
183772
184678
  }
183773
184679
  } catch {
183774
184680
  }
@@ -183791,9 +184697,9 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183791
184697
  const expected = resource.source.type === "asset" ? resource.source.assetId : resource.source.sha256;
183792
184698
  if (!expected) throw new Error("Component source must have a pinned hash.");
183793
184699
  const bytes = await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024);
183794
- 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.");
183795
184701
  const code = bytes.toString(), values = await readJson(root, parameters);
183796
- 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.");
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(", ")}.`);
183797
184703
  for (const b of c.bindings) {
183798
184704
  if (!Object.hasOwn(values, b.name) || typeof values[b.name] !== b.type || b.type === "number" && !Number.isFinite(values[b.name]) || b.type === "string" && values[b.name].length > 8e3) throw new Error(`Parameter ${b.name} must be ${b.type}.`);
183799
184705
  if (b.role === "clip") {
@@ -183802,6 +184708,26 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183802
184708
  values[b.name] = posix4.relative(posix4.dirname(out), values[b.name]);
183803
184709
  }
183804
184710
  }
184711
+ for (const b of c.bindings) if (b.role === "directory") {
184712
+ const directory2 = values[b.name].replace(/\/$/, "");
184713
+ safeStyleResourcePath(directory2);
184714
+ let entries = 0;
184715
+ async function inspect(path2, depth = 0) {
184716
+ if (depth > 4) throw new Error(`Binding ${b.name}: directory exceeds depth 4.`);
184717
+ const absolute = await checkedPath(root, path2, false), info = await lstat8(absolute);
184718
+ if (!info.isDirectory()) throw new Error(`Binding ${b.name}: expected a directory at ${path2}.`);
184719
+ for (const item of await readdir7(absolute, { withFileTypes: true })) {
184720
+ if (++entries > 500) throw new Error(`Binding ${b.name}: directory exceeds 500 entries.`);
184721
+ const child = posix4.join(path2, item.name);
184722
+ safeStyleResourcePath(child);
184723
+ await checkedPath(root, child, false);
184724
+ if (item.isDirectory()) await inspect(child, depth + 1);
184725
+ else if (!item.isFile()) throw new Error(`Binding ${b.name}: directory contains a nonregular file: ${child}.`);
184726
+ }
184727
+ }
184728
+ await inspect(directory2);
184729
+ values[b.name] = (posix4.relative(posix4.dirname(out), directory2) || ".") + (String(b.literal).endsWith("/") ? "/" : "");
184730
+ }
183805
184731
  const spans = bindingSpans(code, c.bindings);
183806
184732
  let prepared = "", cursor = 0;
183807
184733
  for (const span of spans) {
@@ -183810,12 +184736,23 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183810
184736
  }
183811
184737
  prepared += code.slice(cursor);
183812
184738
  const warnings = [];
183813
- const locators = /* @__PURE__ */ new Map();
184739
+ const locators = /* @__PURE__ */ new Map(), locatorResources = /* @__PURE__ */ new Map();
183814
184740
  for (const r of manifest.resources) {
183815
184741
  if (r.source.type === "requirement") continue;
183816
184742
  const original = r.source.type === "local" ? r.source.path : r.source.originalPath;
183817
184743
  if (!original) continue;
183818
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);
183819
184756
  }
183820
184757
  const replacements = [];
183821
184758
  for (const m of prepared.matchAll(/(?:src\s*=\s*["']|href\s*=\s*["']|url\(["']?)([^"')\s>]+)/g)) {
@@ -183826,16 +184763,16 @@ async function prepareComponent(directory, id3, componentId, parameters, out) {
183826
184763
  }
183827
184764
  const original = posix4.normalize(posix4.join(posix4.dirname(c.originPath ?? path), value)), mapped = locators.get(original);
183828
184765
  if (mapped) {
183829
- 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);
183830
184767
  const expected2 = source2.source.type === "asset" ? source2.source.assetId : source2.source.type === "local" ? source2.source.sha256 : void 0;
183831
184768
  const dependency = await readReviewFile(await checkedPath(root, mapped, false), 90 * 1024 * 1024);
183832
- 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);
183833
184770
  replacements.push({ from: m[0], to: m[0].slice(0, -value.length) + posix4.relative(posix4.dirname(out), mapped).split("/").map(encodeURIComponent).join("/") });
183834
184771
  } else warnings.push("Undeclared local dependency: " + original);
183835
184772
  }
183836
184773
  for (const replacement of replacements) prepared = prepared.split(replacement.from).join(replacement.to);
183837
184774
  await atomicWrite(root, out, prepared, { document: false, overwrite: false });
183838
- 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."] };
183839
184776
  }
183840
184777
  async function testStyleTransfer(directory, id3, projectId) {
183841
184778
  const root = await ensureRoot(directory);
@@ -183844,9 +184781,11 @@ async function testStyleTransfer(directory, id3, projectId) {
183844
184781
  const validated = validateDocument(projectPath, raw);
183845
184782
  if (!validated.valid) throw new Error(validated.issues.map((x) => x.message).join("\n"));
183846
184783
  const project = JSON.parse(raw);
183847
- let script = typeof project.script === "string" ? project.script : "";
184784
+ let script = typeof project.script === "string" ? project.script : "", scriptFile = projectPath, scriptField = "script";
183848
184785
  if (!script.trim()) try {
183849
- script = await readText(root, `videos/${projectId}/script.md`);
184786
+ scriptFile = `videos/${projectId}/script.md`;
184787
+ scriptField = void 0;
184788
+ script = await readText(root, scriptFile);
183850
184789
  } catch (e) {
183851
184790
  if (e.code !== "ENOENT") throw e;
183852
184791
  }
@@ -183867,17 +184806,31 @@ async function testStyleTransfer(directory, id3, projectId) {
183867
184806
  }
183868
184807
  const unavailable = t.resourceIds.filter((rid) => !check.resources.some((r) => r.id === rid && ["verified", "present"].includes(r.status)));
183869
184808
  const component = t.componentId ? registry.components.find((c) => c.id === t.componentId) : void 0;
183870
- return { techniqueId: t.id, status: !script.trim() ? "missing_script" : !positions.length ? "anchor_not_found" : positions.length > 1 ? "ambiguous_anchor" : unavailable.length ? "missing_resources" : t.componentId && component?.status !== "parameterized" ? "component_not_ready" : "candidate", truncatedMatches: truncated, suggestedTextRanges: positions.map((start3) => ({ start: start3, end: start3 + t.anchor.text.length })), missingResources: unavailable, requiredParameters: component?.bindings.map((b) => ({ name: b.name, type: b.type, role: b.role })) ?? [], verify: t.verify, reviewConditions: { when: t.when, omitWhen: t.omitWhen, evaluated: false } };
184809
+ return { techniqueId: t.id, status: !script.trim() ? "missing_script" : !positions.length ? "anchor_not_found" : positions.length > 1 ? "ambiguous_anchor" : unavailable.length ? "missing_resources" : t.componentId && component?.status !== "parameterized" ? "component_not_ready" : "candidate", truncatedMatches: truncated, suggestedTextRanges: positions.map((start3) => ({ start: start3, end: start3 + t.anchor.text.length, text: script.slice(start3, start3 + t.anchor.text.length), context: script.slice(Math.max(0, start3 - 80), Math.min(script.length, start3 + t.anchor.text.length + 80)), file: scriptFile, ...scriptField ? { field: scriptField } : {}, line: script.slice(0, start3).split("\n").length })), missingResources: unavailable, requiredParameters: component?.bindings.map((b) => ({ name: b.name, type: b.type, role: b.role })) ?? [], verify: t.verify, reviewConditions: { when: t.when, omitWhen: t.omitWhen, evaluated: false } };
183871
184810
  });
183872
- return { id: id3, projectId, brandId: project.brand, mode: "local_dry_run", rendered: false, creditsUsed: 0, projectChanged: false, transferVerified: false, compatibility: { tokens: target.tokens, captions: target.styleProduction?.captions, audio: target.audioProduction, mediaSources: target.mediaPreferences.sources }, placements, resources: check.resources, issues: check.issues, warnings: [...check.warnings, ...target.warnings, ...!techniques.techniques.length ? ["No structured techniques yet. Add techniques.json to obtain scene suggestions."] : [], "Text ranges are not timestamps. Agent must evaluate semantic fit, brand rules, caption/audio preferences and omit conditions before editing."] };
184811
+ return { id: id3, projectId, brandId: project.brand, mode: "local_dry_run", rendered: false, creditsUsed: 0, projectChanged: false, transferVerified: false, scriptSource: { file: scriptFile, ...scriptField ? { field: scriptField } : {}, offsetUnit: "utf16_code_units", lineBasis: "decoded_script" }, compatibility: { tokens: target.tokens, captions: target.styleProduction?.captions, audio: target.audioProduction, mediaSources: target.mediaPreferences.sources }, placements, resources: check.resources, issues: check.issues, warnings: [...check.warnings, ...target.warnings, ...!techniques.techniques.length ? ["No structured techniques yet. Add techniques.json to obtain scene suggestions."] : [], "Text ranges are not timestamps. Agent must evaluate semantic fit, brand rules, caption/audio preferences and omit conditions before editing."] };
183873
184812
  }
183874
- async function prepareCaptions(directory, projectId, file, out) {
184813
+ async function prepareCaptions(directory, projectId, file, out, styleId2) {
183875
184814
  const root = await ensureRoot(directory);
183876
- assertIdentifier(projectId);
184815
+ if (projectId) assertIdentifier(projectId);
183877
184816
  safeStyleResourcePath(out);
183878
184817
  if (!out.endsWith(".html")) throw new Error("--out must be a new HTML file.");
183879
- const files = await readProjectWorkspace(root, projectId), resolved = await resolveProject(files, projectId), preset = resolved.styleProduction?.captions;
183880
- if (!preset) throw new Error("The project style has no captions.json preset.");
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."] };
184831
+ }
184832
+ const preset = resolved.styleProduction?.captions;
184833
+ if (!preset) throw new Error(`Style ${resolved.project.style} has no captions.json preset.`);
183881
184834
  const cues = validateCaptionCues(await readJson(root, file));
183882
184835
  let fontDataUrl;
183883
184836
  if (preset.enabled && preset.font.resourceId) {
@@ -183887,24 +184840,24 @@ async function prepareCaptions(directory, projectId, file, out) {
183887
184840
  if (!resource || resource.kind !== "font" || resource.source.type === "requirement") throw new Error("Caption font resource is missing; declare and download the exact font.");
183888
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;
183889
184842
  const bytes = await readReviewFile(await checkedPath(root, path, false), 8 * 1024 * 1024);
183890
- 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.");
183891
184844
  const ext = posix4.extname(path).slice(1);
183892
184845
  if (!["woff", "woff2", "ttf", "otf"].includes(ext)) throw new Error("Unsupported caption font format.");
183893
184846
  fontDataUrl = `data:font/${ext};base64,${bytes.toString("base64")}`;
183894
184847
  }
183895
184848
  await atomicWrite(root, out, captionLayer(preset, cues, resolved.output.width, resolved.output.height, fontDataUrl), { document: false, overwrite: false });
183896
- return { projectId, out, enabled: preset.enabled, rendered: false, warnings: resolved.warnings, next: "Load the transparent HTML at output resolution, install the declared font and await renderAt(seconds) for each frame. Cue.crossing and forbiddenZones must be supplied from the actual scene; no face detection is implied." };
184849
+ return { projectId, styleId: resolved.project.style, projectChanged: false, out, enabled: preset.enabled, rendered: false, warnings: resolved.warnings, next: "Load the transparent HTML at output resolution, install the declared font and await renderAt(seconds) for each frame. Cue.crossing and forbiddenZones must be supplied from the actual scene; no face detection is implied." };
183897
184850
  }
183898
184851
 
183899
184852
  // packages/cli/src/style-sources.ts
183900
- import { constants as constants5 } from "node:fs";
183901
- import { open as open6, mkdir as mkdir4, writeFile, rm } from "node:fs/promises";
183902
- 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";
183903
184856
 
183904
184857
  // packages/cli/src/authored-motion.ts
183905
- import { lstat as lstat5, mkdir as mkdir3, open as open5, link as link2, unlink as unlink5 } from "node:fs/promises";
183906
- import { dirname as dirname3, join as join2 } from "node:path";
183907
- 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";
183908
184861
  async function downloadAuthoredSource(client, pin, root, out, fetcher = fetch) {
183909
184862
  return downloadPinnedSource(client, pin, root, out, "motion", fetcher);
183910
184863
  }
@@ -183914,7 +184867,7 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
183914
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.");
183915
184868
  const target = await checkedPath(root, out, false);
183916
184869
  try {
183917
- await lstat5(target);
184870
+ await lstat9(target);
183918
184871
  throw new CliError("FILE_EXISTS", "The output already exists.", "Choose a new archive path.");
183919
184872
  } catch (error) {
183920
184873
  if (error.code !== "ENOENT") throw error;
@@ -183933,23 +184886,23 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
183933
184886
  if (!response.ok) throw new CliError("DOWNLOAD_FAILED", `Source download failed (HTTP ${response.status}).`, "Request a new source link; existing archives were preserved.");
183934
184887
  const reader = response.body?.getReader();
183935
184888
  if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
183936
- const temporary = join2(dirname3(target), `.eb-motion-${randomUUID3()}.tmp`);
184889
+ const temporary = join3(dirname6(target), `.eb-motion-${randomUUID4()}.tmp`);
183937
184890
  let handle;
183938
- const hash8 = createHash5("sha256");
184891
+ const hash9 = createHash8("sha256");
183939
184892
  let size = 0;
183940
184893
  try {
183941
- await mkdir3(dirname3(target), { recursive: true });
184894
+ await mkdir5(dirname6(target), { recursive: true });
183942
184895
  await checkedPath(root, out, false);
183943
- handle = await open5(temporary, "wx", 384);
184896
+ handle = await open9(temporary, "wx", 384);
183944
184897
  for (; ; ) {
183945
184898
  const { done, value } = await reader.read();
183946
184899
  if (done) break;
183947
184900
  size += value.length;
183948
184901
  if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
183949
- hash8.update(value);
184902
+ hash9.update(value);
183950
184903
  await handle.writeFile(value);
183951
184904
  }
183952
- 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.");
183953
184906
  await handle.sync();
183954
184907
  await handle.close();
183955
184908
  await checkedPath(root, out, false);
@@ -183961,18 +184914,18 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
183961
184914
  } finally {
183962
184915
  await handle?.close().catch(() => {
183963
184916
  });
183964
- await unlink5(temporary).catch(() => {
184917
+ await unlink6(temporary).catch(() => {
183965
184918
  });
183966
184919
  }
183967
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." };
183968
184921
  }
183969
184922
 
183970
184923
  // packages/cli/src/style-archive.ts
183971
- import { createHash as createHash6 } from "node:crypto";
184924
+ import { createHash as createHash9 } from "node:crypto";
183972
184925
  import { gunzipSync } from "node:zlib";
183973
184926
  var STYLE_ARCHIVE_MAX_BYTES = 128 * 1024 * 1024;
183974
184927
  var STYLE_UNPACKED_MAX_BYTES = 192 * 1024 * 1024;
183975
- var archiveHash = (bytes) => createHash6("sha256").update(bytes).digest("hex");
184928
+ var archiveHash = (bytes) => createHash9("sha256").update(bytes).digest("hex");
183976
184929
  function safeArchivePath(name) {
183977
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");
183978
184931
  return name;
@@ -185057,7 +186010,7 @@ async function downloadStyle(client, id3, version, root, out) {
185057
186010
  async function prepareStyleSource(root, id3, version, file, out) {
185058
186011
  const selected = getStyleSource(id3, version), guard = styleSourceGuards[id3];
185059
186012
  if (!selected || !guard) throw new Error("This CLI cannot prepare the exact style version. Update EditorBrain; no version was substituted.");
185060
- const input = await checkedPath(root, file, false), handle = await open6(input, constants5.O_RDONLY | constants5.O_NOFOLLOW);
186013
+ const input = await checkedPath(root, file, false), handle = await open10(input, constants9.O_RDONLY | constants9.O_NOFOLLOW);
185061
186014
  let bytes;
185062
186015
  try {
185063
186016
  const stat = await handle.stat();
@@ -185092,13 +186045,13 @@ Un render de demo no certifica transferencia. Revisa el video completo y registr
185092
186045
  files.set("PROJECT-BINDING.md", Buffer.from(guide));
185093
186046
  files.set("PROJECT-BINDING.json", Buffer.from(JSON.stringify(receipt, null, 2) + "\n"));
185094
186047
  const target = await checkedPath(root, out, false);
185095
- await mkdir4(dirname4(target), { recursive: true });
186048
+ await mkdir6(dirname7(target), { recursive: true });
185096
186049
  await checkedPath(root, out, false);
185097
- await mkdir4(target, { mode: 448 });
186050
+ await mkdir6(target, { mode: 448 });
185098
186051
  try {
185099
186052
  for (const [name, data] of files) {
185100
186053
  const destination = await checkedPath(target, name, false);
185101
- await mkdir4(dirname4(destination), { recursive: true });
186054
+ await mkdir6(dirname7(destination), { recursive: true });
185102
186055
  await writeFile(destination, data, { flag: "wx", mode: 384 });
185103
186056
  }
185104
186057
  } catch (error) {
@@ -185219,335 +186172,7 @@ async function teamCommand(client, subcommand, flags) {
185219
186172
 
185220
186173
  // packages/cli/src/personal-resources.ts
185221
186174
  import { basename, extname as extname2, resolve as resolve3 } from "node:path";
185222
- import { randomUUID as randomUUID4 } from "node:crypto";
185223
-
185224
- // packages/cli/src/media-runtime.ts
185225
- import { spawn } from "node:child_process";
185226
- import { createHash as createHash7 } from "node:crypto";
185227
- import { constants as constants6 } from "node:fs";
185228
- import { lstat as lstat6, open as open7, realpath as realpath2 } from "node:fs/promises";
185229
- import { dirname as dirname5, extname, parse, resolve as resolve2 } from "node:path";
185230
- var MediaToolError = class extends CliError {
185231
- constructor(code, message) {
185232
- 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.");
185233
- this.name = "MediaToolError";
185234
- }
185235
- };
185236
- var SUPPORTED_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
185237
- ".mp4",
185238
- ".mov",
185239
- ".m4v",
185240
- ".mkv",
185241
- ".webm",
185242
- ".avi",
185243
- ".mpg",
185244
- ".mpeg",
185245
- ".mts",
185246
- ".m2ts",
185247
- ".ts",
185248
- ".ogv",
185249
- ".wmv",
185250
- ".wav",
185251
- ".mp3",
185252
- ".m4a",
185253
- ".aac",
185254
- ".flac",
185255
- ".ogg",
185256
- ".opus",
185257
- ".aif",
185258
- ".aiff",
185259
- ".ac3",
185260
- ".eac3",
185261
- ".jpg",
185262
- ".jpeg",
185263
- ".png",
185264
- ".webp",
185265
- ".bmp",
185266
- ".tif",
185267
- ".tiff",
185268
- ".gif",
185269
- ".avif",
185270
- ".heic",
185271
- ".heif"
185272
- ]);
185273
- var PROTOCOLS = "file,pipe";
185274
- 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";
185275
- var DEFAULT_TIMEOUT = 3e4;
185276
- var DEFAULT_OUTPUT_LIMIT = 2 * 1024 * 1024;
185277
- function resolveLocalMediaPath(value) {
185278
- 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("\\\\")) {
185279
- throw new MediaToolError("MEDIA_LOCAL_PATH_REQUIRED", "Provide a local filesystem path, not a URL, protocol or network share.");
185280
- }
185281
- return resolve2(value);
185282
- }
185283
- async function assertNoMediaSymlinks(value) {
185284
- const path = resolveLocalMediaPath(value);
185285
- let cursor = path;
185286
- while (cursor !== parse(cursor).root) {
185287
- const info = await lstat6(cursor);
185288
- if (info.isSymbolicLink()) {
185289
- const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath2(cursor) === `/private${cursor}`;
185290
- if (!systemAlias) throw new MediaToolError("MEDIA_SYMLINK", "Symlink media paths are not followed. Use the original local path.");
185291
- }
185292
- cursor = dirname5(cursor);
185293
- }
185294
- return path;
185295
- }
185296
- async function assertLocalMediaFile(value) {
185297
- const path = await assertNoMediaSymlinks(value);
185298
- const info = await lstat6(path);
185299
- if (!info.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
185300
- if (!SUPPORTED_MEDIA_EXTENSIONS.has(extname(path).toLowerCase())) throw new MediaToolError("MEDIA_FORMAT_UNSUPPORTED", "This file extension is not supported for local media inspection.");
185301
- return path;
185302
- }
185303
- function localInputArgs(path) {
185304
- return ["-protocol_whitelist", PROTOCOLS, "-format_whitelist", FORMATS, "-i", resolveLocalMediaPath(path)];
185305
- }
185306
- async function runMediaTool(tool, args, options = {}) {
185307
- if (tool !== "ffmpeg" && tool !== "ffprobe") throw new MediaToolError("MEDIA_TOOL_INVALID", "Unsupported media executable.");
185308
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
185309
- const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_OUTPUT_LIMIT;
185310
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 6e4 || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > 16 * 1024 * 1024) {
185311
- throw new MediaToolError("MEDIA_TOOL_LIMITS_INVALID", "Media runtime limits are outside the supported range.");
185312
- }
185313
- if (!Array.isArray(args) || args.length > 200 || args.some((arg) => typeof arg !== "string" || arg.length > 8192 || arg.includes("\0"))) {
185314
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Invalid media tool arguments.");
185315
- }
185316
- for (let i = 0; i < args.length; i++) {
185317
- const arg = args[i];
185318
- 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") {
185319
- throw new MediaToolError("MEDIA_REMOTE_INPUT_FORBIDDEN", "Only self-contained local media inputs are allowed.");
185320
- }
185321
- if (arg === "-protocol_whitelist" && args[i + 1] !== PROTOCOLS || arg === "-format_whitelist" && args[i + 1] !== FORMATS) {
185322
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "The local media allowlists cannot be widened.");
185323
- }
185324
- if (arg === "-i") {
185325
- await assertLocalMediaFile(args[i + 1] ?? "");
185326
- if (args[i - 4] !== "-protocol_whitelist" || args[i - 3] !== PROTOCOLS || args[i - 2] !== "-format_whitelist" || args[i - 1] !== FORMATS) {
185327
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Every media input must use localInputArgs.");
185328
- }
185329
- }
185330
- }
185331
- return new Promise((resolveResult, reject) => {
185332
- const stdout = [], stderr = [];
185333
- let size = 0, done = false;
185334
- const child = spawn(tool, ["-hide_banner", ...tool === "ffmpeg" ? ["-nostdin"] : [], ...args], { shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
185335
- const fail3 = (error) => {
185336
- if (done) return;
185337
- done = true;
185338
- clearTimeout(timer);
185339
- child.kill("SIGKILL");
185340
- reject(error);
185341
- };
185342
- const timer = setTimeout(() => fail3(new MediaToolError("MEDIA_TOOL_TIMEOUT", "The local media check exceeded its time limit. No complete result is available.")), timeoutMs);
185343
- const collect = (target) => (chunk) => {
185344
- if (done) return;
185345
- size += chunk.length;
185346
- if (size > maxOutputBytes) return fail3(new MediaToolError("MEDIA_TOOL_OUTPUT_LIMIT", "The local media check exceeded its output limit. No complete result is available."));
185347
- target.push(chunk);
185348
- };
185349
- child.stdout.on("data", collect(stdout));
185350
- child.stderr.on("data", collect(stderr));
185351
- 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.")));
185352
- child.on("close", (code) => {
185353
- if (done) return;
185354
- done = true;
185355
- clearTimeout(timer);
185356
- 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."));
185357
- resolveResult({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
185358
- });
185359
- });
185360
- }
185361
- var finite2 = (value) => {
185362
- if (typeof value !== "number" && typeof value !== "string" || value === "") return null;
185363
- const n = Number(value);
185364
- return Number.isFinite(n) ? n : null;
185365
- };
185366
- var nonnegative2 = (value) => {
185367
- const n = finite2(value);
185368
- return n !== null && n >= 0 ? n : null;
185369
- };
185370
- var positiveInteger = (value) => {
185371
- const n = finite2(value);
185372
- return n !== null && Number.isInteger(n) && n > 0 ? n : void 0;
185373
- };
185374
- var rate2 = (value) => {
185375
- if (typeof value !== "string" || !/^\d+(?:\/\d+)?$/.test(value)) return null;
185376
- const [n, d = "1"] = value.split("/");
185377
- const result2 = Number(n) / Number(d);
185378
- return Number.isFinite(result2) && result2 > 0 ? result2 : null;
185379
- };
185380
- var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
185381
- function hasDisplayTransform(stream) {
185382
- const rotate = stream.tags?.rotate;
185383
- if (rotate !== void 0 && (!Number.isFinite(Number(rotate)) || Number(rotate) % 360 !== 0)) return true;
185384
- const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : [];
185385
- return sideData.some((data) => {
185386
- if (!data || typeof data !== "object") return false;
185387
- if (data.rotation !== void 0 && (!Number.isFinite(Number(data.rotation)) || Number(data.rotation) % 360 !== 0)) return true;
185388
- if (data.displaymatrix === void 0) return data.side_data_type === "Display Matrix";
185389
- if (typeof data.displaymatrix !== "string") return true;
185390
- const values = data.displaymatrix.trim().split("\n").flatMap((line) => line.replace(/^[^:]*:/, "").trim().split(/\s+/).map(Number));
185391
- const identity = [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824];
185392
- return values.length !== 9 || values.some((value, index) => value !== identity[index]);
185393
- });
185394
- }
185395
- async function probeLocalMedia(value) {
185396
- const path = await assertLocalMediaFile(value);
185397
- const handle = await open7(path, constants6.O_RDONLY | (constants6.O_NOFOLLOW ?? 0));
185398
- try {
185399
- const before = await handle.stat();
185400
- if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
185401
- 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";
185402
- const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
185403
- const hash8 = createHash7("sha256");
185404
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash8.update(chunk);
185405
- const after = await handle.stat();
185406
- await assertNoMediaSymlinks(path);
185407
- const current2 = await lstat6(path);
185408
- 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.");
185409
- let raw;
185410
- try {
185411
- raw = JSON.parse(stdout);
185412
- } catch {
185413
- throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid metadata.");
185414
- }
185415
- 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.");
185416
- const streams = raw.streams.map((stream, offset) => {
185417
- const type = typeof stream.codec_type === "string" && /^(video|audio|subtitle|data|attachment|unknown)$/.test(stream.codec_type) ? stream.codec_type : "unknown";
185418
- const codec = typeof stream.codec_name === "string" && /^[a-zA-Z0-9_]{1,64}$/.test(stream.codec_name) ? stream.codec_name : null;
185419
- const index = finite2(stream.index);
185420
- return {
185421
- index: index !== null && Number.isInteger(index) && index >= 0 ? index : offset,
185422
- type,
185423
- codec,
185424
- durationSeconds: nonnegative2(stream.duration),
185425
- ...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 } : {},
185426
- ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
185427
- };
185428
- });
185429
- return { path, sha256: hash8.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
185430
- } finally {
185431
- await handle.close();
185432
- }
185433
- }
185434
-
185435
- // packages/cli/src/production-output.ts
185436
- import { constants as constants7 } from "node:fs";
185437
- import { mkdir as mkdir5, open as open8 } from "node:fs/promises";
185438
- import { dirname as dirname6 } from "node:path";
185439
- async function productionOutputPath(root, relativePath) {
185440
- if (!relativePath.startsWith(".editorbrain-local/") || relativePath.split(/[\\/]/).some((p) => !p || p === ".." || p === ".") || /[\\\x00-\x1f\x7f]/.test(relativePath)) {
185441
- 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.");
185442
- }
185443
- return checkedPath(root, relativePath, false);
185444
- }
185445
- async function prepareSampleDirectory(root, path) {
185446
- const target = await productionOutputPath(root, path);
185447
- await mkdir5(dirname6(target), { recursive: true });
185448
- await productionOutputPath(root, path);
185449
- return target;
185450
- }
185451
- async function readProductionJson(root, path) {
185452
- const target = await checkedPath(root, path, false);
185453
- const handle = await open8(target, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
185454
- try {
185455
- const stat = await handle.stat();
185456
- 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.");
185457
- return JSON.parse(await handle.readFile("utf8"));
185458
- } finally {
185459
- await handle.close();
185460
- }
185461
- }
185462
- async function saveProductionReport(root, path, report) {
185463
- const target = await productionOutputPath(root, path);
185464
- if (!path.endsWith(".json")) throw new CliError("INVALID_ARGUMENT", "Report output needs a .json extension.", "Use a new path under .editorbrain-local/.");
185465
- await atomicWrite(root, path, stableJson(report), { document: false, overwrite: false, mode: 384 });
185466
- return target;
185467
- }
185468
- function summarizeProductionReport(value) {
185469
- const r = value;
185470
- const base = { schemaVersion: r.schemaVersion, kind: r.kind, summary: true, mediaUploaded: false, quality: "not_assessed" };
185471
- if (r.kind === "editorbrain.media-inventory") return {
185472
- ...base,
185473
- complete: r.complete,
185474
- contentReviewed: false,
185475
- counts: { assets: r.assets.length, failures: r.failures.length, skipped: r.skipped.length },
185476
- assets: r.assets.slice(0, 8),
185477
- failures: r.failures.slice(0, 5),
185478
- omitted: { assets: Math.max(0, r.assets.length - 8), failures: Math.max(0, r.failures.length - 5), skipped: r.skipped.length },
185479
- 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."
185480
- };
185481
- 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." };
185482
- if (r.kind === "editorbrain.production-plan-check") return {
185483
- ...base,
185484
- valid: r.valid,
185485
- inventoryComplete: r.inventoryComplete,
185486
- observations: r.observations,
185487
- sourceFilesReverified: false,
185488
- counts: { sources: r.coverage.length, findings: r.findings.length, repeatedPairs: r.repeatedPairs ?? 0 },
185489
- 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),
185490
- omittedFindings: Math.max(0, r.findings.length - 8),
185491
- next: "Review source reuse and inspection gaps in the saved report. Observations are agent-declared, not independently certified."
185492
- };
185493
- if (r.kind === "editorbrain.render-check") return {
185494
- ...base,
185495
- complete: r.complete,
185496
- technicalStatus: r.technicalStatus,
185497
- file: r.file,
185498
- checks: r.checks,
185499
- findings: r.findings.slice(0, 8),
185500
- findingsSummary: r.findingsSummary,
185501
- omittedFindings: Math.max(0, r.findings.length - 8),
185502
- next: "Reconcile technical candidates with the brief; inspect the actual video/audio. Technical checks do not assess narrative, aesthetics or SFX audibility."
185503
- };
185504
- if (r.kind === "editorbrain.media-source-search") return {
185505
- ...base,
185506
- complete: r.complete,
185507
- 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 })),
185508
- metadataAbbreviated: true,
185509
- failures: r.failures.slice(0, 5),
185510
- counts: r.counts,
185511
- omitted: { results: Math.max(0, r.results.length - 5), failures: Math.max(0, r.failures.length - 5) },
185512
- searchExhaustive: false,
185513
- rightsVerified: false,
185514
- next: "Inspect relevant source pages and media. These archives supplement web image/video search; empty results do not prove absence on the internet."
185515
- };
185516
- if (r.kind === "editorbrain.evidence-check") return {
185517
- ...base,
185518
- valid: r.valid,
185519
- inventoryComplete: r.inventoryComplete,
185520
- observations: r.observations,
185521
- sourceFilesReverified: false,
185522
- factualTruth: "not_assessed",
185523
- reuseRights: "not_assessed",
185524
- findings: r.findings.slice(0, 8),
185525
- omitted: { findings: Math.max(0, r.findings.length - 8) }
185526
- };
185527
- if (r.kind === "editorbrain.audio-check") return {
185528
- ...base,
185529
- complete: r.complete,
185530
- technicalStatus: r.technicalStatus,
185531
- file: r.file,
185532
- fileStable: r.fileStable,
185533
- coverage: r.coverage,
185534
- measurements: r.measurements.slice(0, 8),
185535
- errorCode: r.errorCode,
185536
- creativeQuality: r.creativeQuality,
185537
- omitted: { measurements: Math.max(0, r.measurements.length - 8) },
185538
- next: "Measurements describe this exact file. Listen for intelligibility, pronunciation, SFX and sync when the modality is available."
185539
- };
185540
- if (r.kind === "editorbrain.motion-review") return {
185541
- ...base,
185542
- 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,
185543
- 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 })),
185544
- omittedGeometryReviews: Math.max(0, r.geometryReviews.length - 3),
185545
- next: "This plans samples and checks declared boxes only. Render/view those frames; read saved details for omitted candidates and intentional overlaps."
185546
- };
185547
- throw new CliError("INVALID_REPORT", "Unknown production report kind.", "Use media inventory/sample or production check/plan-check.");
185548
- }
185549
-
185550
- // packages/cli/src/personal-resources.ts
186175
+ import { randomUUID as randomUUID5 } from "node:crypto";
185551
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" };
185552
186177
  var fail = (message) => {
185553
186178
  throw new CliError("INVALID_RESOURCE", message, "Read editorbrain help and references/personal-resources.md. No upload or paid analysis is automatic.");
@@ -185588,7 +186213,7 @@ async function registerLocalResource(client, root, file, options = {}) {
185588
186213
  } while (!existing && after);
185589
186214
  if (existing) break;
185590
186215
  }
185591
- const id3 = existing?.id ?? randomUUID4();
186216
+ const id3 = existing?.id ?? randomUUID5();
185592
186217
  const result2 = existing ? await client.request("/v1/resources/" + id3) : await client.request("/v1/resources/" + id3, { method: "PUT", body: { resource, expectedRevision: 0 } });
185593
186218
  const me = await client.request("/v1/me");
185594
186219
  const namespace = (await sha256(client.url + "\n" + me.workspaceId)).slice(0, 32), path = `.editorbrain-local/resources/${namespace}/${id3}.json`;
@@ -185679,19 +186304,111 @@ async function personalResourceCommand(client, root, command, arg, flags) {
185679
186304
 
185680
186305
  // packages/cli/src/update.ts
185681
186306
  import { execFile } from "node:child_process";
185682
- import { lstat as lstat9, 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";
185683
186308
  import { homedir as homedir2 } from "node:os";
185684
- 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";
185685
186310
  import { promisify } from "node:util";
185686
186311
 
185687
186312
  // packages/cli/src/agent-guidance.ts
185688
- import { createHash as createHash8 } from "node:crypto";
185689
- import { constants as constants8 } from "node:fs";
185690
- import { lstat as lstat7, open as open9, readdir as readdir4, 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";
185691
186316
  import { fileURLToPath } from "node:url";
185692
186317
 
185693
186318
  // packages/cli/src/agent-guidance-history.ts
185694
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
+ },
186366
+ {
186367
+ "version": "0.42.0",
186368
+ "archiveSha256": "ecd32addc5532a06e23730f2b861ba43c06e006c38250da11ace63c5aa67e7a1",
186369
+ "files": {
186370
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
186371
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
186372
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
186373
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
186374
+ "editorbrain/references/cli-mcp.md": "2c34ed7f896865e71959562bcc61b5a34292d6a9a4c14690f0c28d00875da75c",
186375
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
186376
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
186377
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
186378
+ "editorbrain/references/editorial-evidence.md": "79ed5bd90eb903014313c32a1e337822c5cb454e642bcfa852dcb77d30a9392e",
186379
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
186380
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
186381
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
186382
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
186383
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
186384
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
186385
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
186386
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
186387
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
186388
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
186389
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
186390
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
186391
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
186392
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
186393
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
186394
+ "editorbrain/references/onboarding.md": "b842dac368455b670543d9a0defdad91708c10788d1474ddfa6b31ca929e930b",
186395
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
186396
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
186397
+ "editorbrain/references/production-continuity.md": "4b020f5bab47f6b5619387b623339602b87202fec03d85a7a26737209e0b5d4e",
186398
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
186399
+ "editorbrain/references/search-brief.md": "1bd2514f961522675047910f001f33da035382e48e933bc5eadb9d7d01455a0d",
186400
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
186401
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
186402
+ "editorbrain-motion/SKILL.md": "57292f3a48cc8f1fc2d89f2cc054a3ceabeda9422958fa708f273c662867d5ae",
186403
+ "editorbrain/SKILL.md": "028e66a96eb6fd2382387472727ee1f55ab113a3109917eda57050f8544fde9d",
186404
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
186405
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
186406
+ "editorbrain/references/studio.md": "673377f4534d9a5edd15a75f1ba9acb589458904dfc34332c30033e03801b6a8",
186407
+ "editorbrain/references/style-creator.md": "00c613c9620e2ee6296662ce70902edcf06652b0fec93feffdcf9ce75f86c1dc",
186408
+ "editorbrain/references/style-source.md": "983fa21b4606c3cdc41b2fa4386ddc8f77a1b14ae782aad8774c000696c14de1",
186409
+ "editorbrain/references/workspace-files.md": "9ded0de75ccbbd0ed382b48c0ccaa6bc9ba1e37613fe47cd0c95a36dffd7e601"
186410
+ }
186411
+ },
185695
186412
  {
185696
186413
  "version": "0.41.2",
185697
186414
  "archiveSha256": "fefa3658ab5fc64f29d751d9289f5c3e20ff0209a6e8e57908a7c4173853a541",
@@ -186444,8 +187161,8 @@ function bundledSkillDirectory(moduleUrl = import.meta.url, skillName = "editorb
186444
187161
  }
186445
187162
  async function readBytes(root, path) {
186446
187163
  const target = await checkedPath(root, path, false);
186447
- if (!(await lstat7(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
186448
- const handle = await open9(target, constants8.O_RDONLY | constants8.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);
186449
187166
  try {
186450
187167
  if (!(await handle.stat()).isFile()) throw new Error(`Not a regular file: ${path}`);
186451
187168
  return await handle.readFile();
@@ -186466,7 +187183,7 @@ async function loadSkill(directory) {
186466
187183
  const files = /* @__PURE__ */ new Map();
186467
187184
  async function walk(path = "") {
186468
187185
  const location2 = path ? await checkedPath(root, path, false) : root;
186469
- const entries = await readdir4(location2, { withFileTypes: true });
187186
+ const entries = await readdir8(location2, { withFileTypes: true });
186470
187187
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
186471
187188
  const child = path ? `${path}/${entry.name}` : entry.name;
186472
187189
  if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed in bundled skill: ${child}`);
@@ -186522,7 +187239,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
186522
187239
  for (const selected of agents) {
186523
187240
  const to = destinations[selected].directory, from = to.replace(/editorbrain$/, "editorharness");
186524
187241
  const oldPath = await checkedPath(root, from, false), newPath = await checkedPath(root, to, false);
186525
- const exists3 = async (path) => lstat7(path).then(() => true, (error) => {
187242
+ const exists3 = async (path) => lstat10(path).then(() => true, (error) => {
186526
187243
  if (error.code === "ENOENT") return false;
186527
187244
  throw error;
186528
187245
  });
@@ -186540,12 +187257,12 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
186540
187257
  await loadSkill(await checkedPath(root, migration.from, false));
186541
187258
  const target = await checkedPath(root, migration.to, false);
186542
187259
  try {
186543
- await lstat7(target);
187260
+ await lstat10(target);
186544
187261
  throw new Error("Skill destination appeared during migration; no overwrite allowed.");
186545
187262
  } catch (error) {
186546
187263
  if (error.code !== "ENOENT") throw error;
186547
187264
  }
186548
- await rename3(await checkedPath(root, migration.from, false), target);
187265
+ await rename4(await checkedPath(root, migration.from, false), target);
186549
187266
  }
186550
187267
  for (const file of files) {
186551
187268
  let status;
@@ -186555,7 +187272,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
186555
187272
  } catch (error) {
186556
187273
  if (error.code !== "EEXIST") throw error;
186557
187274
  const existing = await readBytes(root, file.path);
186558
- const existingHash = createHash8("sha256").update(existing).digest("hex");
187275
+ const existingHash = createHash10("sha256").update(existing).digest("hex");
186559
187276
  const pristine = file.kind === "skill" && (previousHashesBySkill[file.skillName][file.relativePath]?.includes(existingHash) || isVerifiedHistoricalGuidance(file.skillName, file.relativePath, existingHash));
186560
187277
  const oldPointer = Buffer.from(file.content.toString().replaceAll("/skills/editorbrain/", "/skills/editorharness/"));
186561
187278
  if (!existing.equals(file.content) && (pristine || file.kind === "entryPoint" && existing.equals(oldPointer))) {
@@ -186592,19 +187309,19 @@ async function installAgentGuidance(directory, agent = "both") {
186592
187309
  }
186593
187310
 
186594
187311
  // packages/cli/src/skill-installations.ts
186595
- import { createHash as createHash9, randomUUID as randomUUID5 } from "node:crypto";
186596
- import { readFile as readFile2, readdir as readdir5 } 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";
186597
187314
  import { homedir } from "node:os";
186598
- import { isAbsolute, join as join4 } from "node:path";
187315
+ import { isAbsolute, join as join5 } from "node:path";
186599
187316
 
186600
187317
  // packages/cli/src/doctor.ts
186601
187318
  import { readFile } from "node:fs/promises";
186602
187319
  import { resolve as resolve4 } from "node:path";
186603
187320
 
186604
187321
  // packages/cli/src/integrations.ts
186605
- import { constants as constants9 } from "node:fs";
186606
- import { lstat as lstat8, open as open10 } from "node:fs/promises";
186607
- function object7(value) {
187322
+ import { constants as constants11 } from "node:fs";
187323
+ import { lstat as lstat11, open as open12 } from "node:fs/promises";
187324
+ function object8(value) {
186608
187325
  return value !== null && typeof value === "object" && !Array.isArray(value);
186609
187326
  }
186610
187327
  function invalidState(write) {
@@ -186617,13 +187334,13 @@ function invalidState(write) {
186617
187334
  );
186618
187335
  }
186619
187336
  function integrationState(value, write = false) {
186620
- if (!object7(value) || !["member", "connection"].includes(value.scope) || !Number.isSafeInteger(value.revision) || value.revision < 0 || !(value.updatedAt === null || typeof value.updatedAt === "string" && value.updatedAt.length <= 64 && Number.isFinite(Date.parse(value.updatedAt))) || !Array.isArray(value.entries) || !Array.isArray(value.catalog)) throw invalidState(write);
187337
+ if (!object8(value) || !["member", "connection"].includes(value.scope) || !Number.isSafeInteger(value.revision) || value.revision < 0 || !(value.updatedAt === null || typeof value.updatedAt === "string" && value.updatedAt.length <= 64 && Number.isFinite(Date.parse(value.updatedAt))) || !Array.isArray(value.entries) || !Array.isArray(value.catalog)) throw invalidState(write);
186621
187338
  const providers = /* @__PURE__ */ new Set();
186622
187339
  for (const entry of value.entries) {
186623
- if (!object7(entry) || typeof entry.providerId !== "string" || !entry.providerId || entry.providerId.length > 120 || providers.has(entry.providerId) || typeof entry.enabled !== "boolean" || typeof entry.accessMethod !== "string" || !entry.accessMethod || entry.accessMethod.length > 64 || !object7(entry.preferences)) throw invalidState(write);
187340
+ if (!object8(entry) || typeof entry.providerId !== "string" || !entry.providerId || entry.providerId.length > 120 || providers.has(entry.providerId) || typeof entry.enabled !== "boolean" || typeof entry.accessMethod !== "string" || !entry.accessMethod || entry.accessMethod.length > 64 || !object8(entry.preferences)) throw invalidState(write);
186624
187341
  providers.add(entry.providerId);
186625
187342
  }
186626
- if (value.catalog.some((provider) => !object7(provider) || typeof provider.id !== "string" || !provider.id)) throw invalidState(write);
187343
+ if (value.catalog.some((provider) => !object8(provider) || typeof provider.id !== "string" || !provider.id)) throw invalidState(write);
186627
187344
  return {
186628
187345
  scope: value.scope,
186629
187346
  revision: value.revision,
@@ -186636,13 +187353,13 @@ async function readIntegrationSettings(file) {
186636
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.");
186637
187354
  const changedFile = () => new CliError("INVALID_ARGUMENT", "Integration settings changed while being read.", "Choose a stable regular settings file and try again.");
186638
187355
  const limit = 16 * 1024;
186639
- const before = await lstat8(file);
187356
+ const before = await lstat11(file);
186640
187357
  if (!before.isFile() || before.isSymbolicLink() || before.size > limit) throw invalidFile();
186641
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;
186642
- const handle = await open10(file, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
187359
+ const handle = await open12(file, constants11.O_RDONLY | constants11.O_NOFOLLOW | constants11.O_NONBLOCK);
186643
187360
  try {
186644
187361
  const opened = await handle.stat();
186645
- const current2 = await lstat8(file);
187362
+ const current2 = await lstat11(file);
186646
187363
  if (!unchanged2(opened) || !unchanged2(current2)) throw changedFile();
186647
187364
  const bytes = Buffer.alloc(limit + 1);
186648
187365
  let length = 0;
@@ -186652,7 +187369,7 @@ async function readIntegrationSettings(file) {
186652
187369
  length += bytesRead;
186653
187370
  }
186654
187371
  const after = await handle.stat();
186655
- const finalPath = await lstat8(file);
187372
+ const finalPath = await lstat11(file);
186656
187373
  if (length > limit || length !== opened.size || !unchanged2(after) || !unchanged2(finalPath)) throw changedFile();
186657
187374
  try {
186658
187375
  return JSON.parse(bytes.subarray(0, length).toString("utf8"));
@@ -186860,10 +187577,10 @@ async function diagnose(options, fetcher = fetch, probeTool = probe) {
186860
187577
 
186861
187578
  // packages/cli/src/skill-installations.ts
186862
187579
  function installationRegistry() {
186863
- 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");
186864
187581
  }
186865
187582
  function recordName(directory, scope) {
186866
- return createHash9("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
187583
+ return createHash11("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
186867
187584
  }
186868
187585
  function validateRecord(value) {
186869
187586
  const r = value;
@@ -186891,7 +187608,7 @@ async function listInstallations(registry = installationRegistry()) {
186891
187608
  if (error.code === "ENOENT") return [];
186892
187609
  throw error;
186893
187610
  }
186894
- const names = (await readdir5(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();
186895
187612
  if (names.length > 1e3) throw new Error("Too many registered installations. Update a specific directory.");
186896
187613
  const records = [];
186897
187614
  for (const name of names) {
@@ -186927,7 +187644,7 @@ async function installManagedGuidance(directory, agent, options = {}) {
186927
187644
  const previous = await readInstallation(root, scope, options.registry);
186928
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.");
186929
187646
  const target = parseAgentTarget(agent ?? previous?.agent);
186930
- 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() });
186931
187648
  const result2 = await install();
186932
187649
  try {
186933
187650
  await rememberGuidance(result2, scope, options.registry);
@@ -186948,7 +187665,7 @@ async function pinGuidance(directory, pinned, registry = installationRegistry())
186948
187665
  for (const agent of record13.agent === "both" ? ["codex", "claude"] : [record13.agent]) {
186949
187666
  for (const skill of BUNDLED_SKILLS) for (const path of await bundledGuidanceFiles(skill)) {
186950
187667
  const current2 = await readText(root, `${installedSkillDirectory(agent, skill)}/${path}`, false);
186951
- const expected = await readFile2(join4(bundledSkillDirectory(void 0, skill), path), "utf8");
187668
+ const expected = await readFile2(join5(bundledSkillDirectory(void 0, skill), path), "utf8");
186952
187669
  if (current2 !== expected) throw new Error("Project instructions differ from this release; resolve them before pinning.");
186953
187670
  }
186954
187671
  }
@@ -186994,18 +187711,18 @@ async function latestPublishedVersion(fetcher = fetch) {
186994
187711
  }
186995
187712
  }
186996
187713
  async function npmEntrypoint(env = process.env) {
186997
- 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")];
186998
187715
  for (const directory of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
186999
- candidates.push(join5(directory, "node_modules/npm/bin/npm-cli.js"));
187716
+ candidates.push(join6(directory, "node_modules/npm/bin/npm-cli.js"));
187000
187717
  try {
187001
- candidates.push(await realpath3(join5(directory, "npm")));
187718
+ candidates.push(await realpath3(join6(directory, "npm")));
187002
187719
  } catch {
187003
187720
  }
187004
187721
  }
187005
187722
  for (const candidate of candidates) {
187006
187723
  if (!candidate || !candidate.endsWith("npm-cli.js")) continue;
187007
187724
  try {
187008
- if ((await lstat9(candidate)).isFile()) return candidate;
187725
+ if ((await lstat12(candidate)).isFile()) return candidate;
187009
187726
  } catch {
187010
187727
  }
187011
187728
  }
@@ -187039,9 +187756,9 @@ async function installPublishedCli(version, runner = exec) {
187039
187756
  );
187040
187757
  }
187041
187758
  try {
187042
- 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"));
187043
187760
  if (metadata.name !== "editorbrain" || metadata.version !== version || metadata.bin?.editorbrain !== "bin/editorbrain.mjs") throw new Error("Unexpected installed package");
187044
- const executable = join5(root, "editorbrain/bin/editorbrain.mjs");
187761
+ const executable = join6(root, "editorbrain/bin/editorbrain.mjs");
187045
187762
  const result2 = JSON.parse((await runner(process.execPath, [executable, "version"], { timeout: 15e3, maxBuffer: 65536 })).stdout);
187046
187763
  if (result2.version !== version) throw new Error("Unexpected executable version");
187047
187764
  return executable;
@@ -187076,7 +187793,7 @@ async function detectAgents(root) {
187076
187793
  for (const skill of BUNDLED_SKILLS) {
187077
187794
  const file = await checkedPath(root, `${installedSkillDirectory(agent, skill)}/SKILL.md`, false);
187078
187795
  try {
187079
- if ((await lstat9(file)).isFile()) {
187796
+ if ((await lstat12(file)).isFile()) {
187080
187797
  found.push(agent);
187081
187798
  break;
187082
187799
  }
@@ -187262,8 +187979,8 @@ async function projectProgressCommand(client, command, flags) {
187262
187979
  }
187263
187980
 
187264
187981
  // packages/cli/src/event-mix.ts
187265
- import { mkdir as mkdir6, readFile as readFile4, writeFile as writeFile2, unlink as unlink6 } from "node:fs/promises";
187266
- 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";
187267
187984
  function validateEventCues(value, duration) {
187268
187985
  const v = value;
187269
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.");
@@ -187302,7 +188019,7 @@ function floats(bytes) {
187302
188019
  async function decode(file, target) {
187303
188020
  await runMediaTool("ffmpeg", ["-v", "error", "-n", ...localInputArgs(file), "-map", "0:a:0", "-vn", "-ar", "48000", "-ac", "2", "-f", "f32le", target], { timeoutMs: 6e5 });
187304
188021
  const b = await readFile4(target);
187305
- await unlink6(target);
188022
+ await unlink7(target);
187306
188023
  return floats(b);
187307
188024
  }
187308
188025
  function wav(data) {
@@ -187338,12 +188055,12 @@ async function mixEvents(options) {
187338
188055
  sources.push(source2);
187339
188056
  }
187340
188057
  const directory = await productionOutputPath(options.root, options.out);
187341
- await mkdir6(dirname8(directory), { recursive: true, mode: 448 });
188058
+ await mkdir7(dirname9(directory), { recursive: true, mode: 448 });
187342
188059
  await productionOutputPath(options.root, options.out);
187343
- await mkdir6(directory, { mode: 448 });
187344
- 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 = [];
187345
188062
  for (let i = 0; i < cues.length; i++) {
187346
- const effect = await decode(sources[i].path, join6(directory, "effect.raw"));
188063
+ const effect = await decode(sources[i].path, join7(directory, "effect.raw"));
187347
188064
  records.push({ ...cues[i], sourceSha256: sources[i].sha256, sampleFrames: effect.length / 2, ...addEventPcm(mix, effect, cues[i].time, cues[i].peak) });
187348
188065
  }
187349
188066
  const cuePlan = { durationSeconds: mix.length / 2 / 48e3, hookEndSeconds, cues: records.map((c) => {
@@ -187360,16 +188077,16 @@ async function mixEvents(options) {
187360
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.");
187361
188078
  for (const s of [voice, ...sources]) if ((await probeLocalMedia(s.path)).sha256 !== s.sha256) throw new Error("Audio source changed during mix.");
187362
188079
  if (options.context && !await options.context.validateContext()) throw new Error("Project preferences changed during the mix. Refresh context; no final mix was written.");
187363
- const path = join6(directory, "mix.wav");
188080
+ const path = join7(directory, "mix.wav");
187364
188081
  await writeFile2(path, wav(mix), { flag: "wx", mode: 384 });
187365
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." };
187366
- 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 });
187367
188084
  return report;
187368
188085
  }
187369
188086
 
187370
188087
  // packages/cli/src/production-sheet.ts
187371
- import { mkdir as mkdir7, readFile as readFile5, writeFile as writeFile3, unlink as unlink7 } from "node:fs/promises";
187372
- 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";
187373
188090
  var esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
187374
188091
  function freezeIntervals(log, duration) {
187375
188092
  const result2 = [];
@@ -187408,13 +188125,13 @@ async function createProductionSheet(options) {
187408
188125
  if (options.platform && input.platform && options.platform !== input.platform) throw new Error("Platform flag conflicts with review profile.");
187409
188126
  const platform = options.platform ?? input.platform;
187410
188127
  const directory = await productionOutputPath(options.root, options.out);
187411
- await mkdir7(dirname9(directory), { recursive: true, mode: 448 });
188128
+ await mkdir8(dirname10(directory), { recursive: true, mode: 448 });
187412
188129
  await productionOutputPath(options.root, options.out);
187413
- await mkdir7(directory, { mode: 448 });
187414
- const raw = join7(directory, "samples.gray");
187415
- 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 });
187416
188133
  const data = await readFile5(raw);
187417
- await unlink7(raw);
188134
+ await unlink8(raw);
187418
188135
  const count = data.length / (96 * 96);
187419
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.");
187420
188137
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new Error("Source changed during review.");
@@ -187428,15 +188145,15 @@ async function createProductionSheet(options) {
187428
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>`;
187429
188146
  }).join("");
187430
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>`;
187431
- await writeFile3(join7(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
187432
- await writeFile3(join7(directory, "index.html"), html, { flag: "wx", mode: 384 });
187433
- 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 };
187434
188151
  }
187435
188152
 
187436
188153
  // packages/cli/src/presenter-matte.ts
187437
188154
  import { spawn as spawn2 } from "node:child_process";
187438
- import { mkdir as mkdir8, writeFile as writeFile4, rename as rename4, unlink as unlink8 } from "node:fs/promises";
187439
- 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";
187440
188157
 
187441
188158
  // packages/cli/src/presenter-matte-source.ts
187442
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';
@@ -187498,10 +188215,10 @@ async function generatePresenterMatte(options) {
187498
188215
  const video = videos[0], plan = planPresenterMatte(source2.durationSeconds, video.fps);
187499
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.");
187500
188217
  const dir = await productionOutputPath(options.root, options.out);
187501
- await mkdir8(dirname10(dir), { recursive: true, mode: 448 });
188218
+ await mkdir9(dirname11(dir), { recursive: true, mode: 448 });
187502
188219
  await productionOutputPath(options.root, options.out);
187503
- await mkdir8(dir, { mode: 448 });
187504
- 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");
187505
188222
  await writeFile4(swift, presenterMatteSource, { flag: "wx", mode: 384 });
187506
188223
  try {
187507
188224
  await runLocal("swiftc", ["-O", swift, "-o", binary], 12e4);
@@ -187509,21 +188226,21 @@ async function generatePresenterMatte(options) {
187509
188226
  const [clock, matteClock, mask, after] = await Promise.all([readFrameClock(source2.path), readFrameClock(result2), probeLocalMedia(result2), probeLocalMedia(source2.path)]);
187510
188227
  assertMatteClocks(clock, matteClock);
187511
188228
  if (after.sha256 !== source2.sha256) throw new Error("Source changed during segmentation.");
187512
- const finalPath = join8(dir, "matte.mov");
187513
- await rename4(result2, finalPath);
188229
+ const finalPath = join9(dir, "matte.mov");
188230
+ await rename5(result2, finalPath);
187514
188231
  mask.path = finalPath;
187515
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." };
187516
- 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 });
187517
188234
  return report;
187518
188235
  } finally {
187519
- await unlink8(binary).catch(() => {
188236
+ await unlink9(binary).catch(() => {
187520
188237
  });
187521
188238
  }
187522
188239
  }
187523
188240
 
187524
188241
  // packages/cli/src/sfx.ts
187525
- import { readdir as readdir6, lstat as lstat10 } from "node:fs/promises";
187526
- 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";
187527
188244
 
187528
188245
  // packages/cli/src/production-context.ts
187529
188246
  async function prepareProductionContext(root, projectId, client) {
@@ -187533,8 +188250,8 @@ async function prepareProductionContext(root, projectId, client) {
187533
188250
  const remote = async () => {
187534
188251
  const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
187535
188252
  const snapshot = result2.editorialSnapshot;
187536
- 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.");
187537
- 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.");
187538
188255
  const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
187539
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.");
187540
188257
  return snapshot.contextVersion;
@@ -187563,14 +188280,14 @@ var localPath = (id3) => {
187563
188280
  };
187564
188281
  async function indexSfx(directory, input, bankId) {
187565
188282
  const root = await ensureRoot(directory), target = localPath(bankId), folder = await assertNoMediaSymlinks(input);
187566
- if (!(await lstat10(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.");
187567
188284
  const entries = [], paths2 = {}, failures = [];
187568
- const files = await readdir6(folder, { withFileTypes: true });
188285
+ const files = await readdir10(folder, { withFileTypes: true });
187569
188286
  const selected = files.filter((e) => e.isFile() && [".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aif", ".aiff"].includes(extname3(e.name).toLowerCase()));
187570
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.");
187571
188288
  for (const file of selected.sort((a, b) => a.name.localeCompare(b.name))) {
187572
188289
  try {
187573
- const probe2 = await probeLocalMedia(join9(folder, file.name));
188290
+ const probe2 = await probeLocalMedia(join10(folder, file.name));
187574
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.");
187575
188292
  const id3 = "sfx-" + probe2.sha256.slice(0, 24);
187576
188293
  if (paths2[id3]) continue;
@@ -187633,8 +188350,8 @@ async function remoteSfx(client, subcommand, params) {
187633
188350
  }
187634
188351
 
187635
188352
  // packages/cli/src/media-preview.ts
187636
- import { chmod, link as link3, mkdtemp, rm as rm2 } from "node:fs/promises";
187637
- 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";
187638
188355
  async function prepareMediaPreview(root, file, out, quality = 720, audioStream) {
187639
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/.");
187640
188357
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
@@ -187647,14 +188364,14 @@ async function prepareMediaPreview(root, file, out, quality = 720, audioStream)
187647
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.");
187648
188365
  const selected = audioStream === void 0 ? audio[0] : audio.find((s) => s.index === audioStream);
187649
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.");
187650
- 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-"));
187651
188368
  try {
187652
- const prepared = join10(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
188369
+ const prepared = join11(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
187653
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 });
187654
188371
  const result2 = await probeLocalMedia(prepared);
187655
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.");
187656
188373
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during compression.", "Retry with a stable original.");
187657
- await chmod(prepared, 384);
188374
+ await chmod2(prepared, 384);
187658
188375
  await link3(prepared, target);
187659
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." };
187660
188377
  } finally {
@@ -187664,8 +188381,8 @@ async function prepareMediaPreview(root, file, out, quality = 720, audioStream)
187664
188381
 
187665
188382
  // packages/cli/src/studio-audio.ts
187666
188383
  import { link as link4, mkdtemp as mkdtemp2, readFile as readFile6, rm as rm3 } from "node:fs/promises";
187667
- import { dirname as dirname12, join as join11 } from "node:path";
187668
- 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";
187669
188386
  async function prepareStudioAudio(root, file, out, streamIndex) {
187670
188387
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
187671
188388
  const audio = source2.streams.filter((stream) => stream.type === "audio");
@@ -187675,16 +188392,16 @@ async function prepareStudioAudio(root, file, out, streamIndex) {
187675
188392
  if (!selected) throw new CliError("INVALID_ARGUMENT", "The selected stream is not an audio track.", "Inspect media inventory before selecting a track.");
187676
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.");
187677
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.");
187678
- 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-"));
187679
188396
  try {
187680
- const prepared = join11(temp, "audio.wav");
188397
+ const prepared = join12(temp, "audio.wav");
187681
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 });
187682
188399
  const verified = await probeLocalMedia(prepared);
187683
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.");
187684
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.");
187685
- 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");
187686
188403
  await link4(prepared, target);
187687
- 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." };
187688
188405
  } finally {
187689
188406
  await rm3(temp, { recursive: true, force: true });
187690
188407
  }
@@ -187881,9 +188598,9 @@ async function setup(options, runner = runHost) {
187881
188598
 
187882
188599
  // packages/cli/src/onboarding.ts
187883
188600
  import { createServer } from "node:http";
187884
- import { randomBytes, createHash as createHash11 } from "node:crypto";
187885
- import { join as join12, dirname as dirname13 } from "node:path";
187886
- 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";
187887
188604
 
187888
188605
  // packages/cli/src/onboarding-brand.ts
187889
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';
@@ -188695,7 +189412,7 @@ async function syncOnboardingDocuments(client, root, files, options) {
188695
189412
  // packages/cli/src/onboarding.ts
188696
189413
  var failure = (code, message, hint = "Reopen onboarding against the current files. Nothing is overwritten silently.") => new CliError(code, message, hint);
188697
189414
  function starterOutputId(brandId2) {
188698
- 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)}`;
188699
189416
  }
188700
189417
  function scaffold(brandId2, projectId) {
188701
189418
  const files = Object.fromEntries(Object.entries(createWorkspace({ brand: brandId2, project: projectId })).filter(([p]) => !p.startsWith(`.editorbrain/brands/${brandId2}/`)));
@@ -188751,14 +189468,14 @@ async function createOnboarding(options) {
188751
189468
  const directory = options.out ?? `.editorbrain-local/onboarding/${brandId2}-${Date.now()}-${randomBytes(3).toString("hex")}`;
188752
189469
  await productionOutputPath(root, `${directory}/session.json`);
188753
189470
  const target = await checkedPath(root, directory, false);
188754
- await mkdir9(dirname13(target), { recursive: true });
188755
- await mkdir9(target);
189471
+ await mkdir10(dirname14(target), { recursive: true });
189472
+ await mkdir10(target);
188756
189473
  const saved = await snapshots(root, brandId2, projectId), files = Object.fromEntries(Object.entries(saved).flatMap(([p, s]) => s ? [[p, s.content]] : []));
188757
189474
  const intake = onboardingIntakeFromFiles(brandId2, files);
188758
189475
  const session = { schemaVersion: 1, kind: "editorbrain.onboarding", brandId: brandId2, projectId, intake, snapshots: saved };
188759
189476
  await atomicWrite(root, `${directory}/session.json`, stableJson(session), { document: false, overwrite: false, mode: 384 });
188760
189477
  await atomicWrite(root, `${directory}/index.html`, renderOnboardingArtifact({ intake, requiresIdentity: saved[`.editorbrain/brands/${brandId2}/brand.md`] === null }), { document: false, overwrite: false, mode: 384 });
188761
- 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." };
188762
189479
  }
188763
189480
  async function applyOnboarding(options) {
188764
189481
  const root = await ensureRoot(options.directory);
@@ -188789,7 +189506,7 @@ async function applyOnboarding(options) {
188789
189506
  if (now !== current2[item.path]?.content) throw failure("ONBOARDING_CONFLICT", `Document changed while applying: ${item.path}`);
188790
189507
  await atomicWrite(root, item.path, item.content, { overwrite: now !== void 0 });
188791
189508
  }
188792
- 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 });
188793
189510
  }
188794
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." };
188795
189512
  }, { migrateLegacy: !options.dryRun });
@@ -188798,7 +189515,7 @@ async function syncOnboarding(client, options) {
188798
189515
  const root = await ensureRoot(options.directory);
188799
189516
  return withWorkspaceLock(root, async () => {
188800
189517
  const session = await readSession(root, options.session);
188801
- const receipt = await readProductionJson(root, `${dirname13(options.session)}/applied.json`);
189518
+ const receipt = await readProductionJson(root, `${dirname14(options.session)}/applied.json`);
188802
189519
  if (receipt.brandId !== session.brandId || receipt.projectId !== session.projectId) throw failure("ONBOARDING_NOT_APPLIED", "Apply the reviewed choices locally before syncing.");
188803
189520
  const files = {};
188804
189521
  for (const path of paths(session.brandId, session.projectId)) {
@@ -188815,7 +189532,7 @@ async function syncOnboarding(client, options) {
188815
189532
  async function serveOnboarding(options) {
188816
189533
  const root = await ensureRoot(options.directory), session = await readSession(root, options.session), seconds = options.timeoutSeconds ?? 1800;
188817
189534
  if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) throw failure("INVALID_ARGUMENT", "Timeout must be between 1 and 3600 seconds.");
188818
- 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`;
188819
189536
  let origin = "", consumed = false, busy = false, server;
188820
189537
  let complete, reject;
188821
189538
  const done = new Promise((yes, no) => {
@@ -188855,7 +189572,7 @@ async function serveOnboarding(options) {
188855
189572
  await atomicWrite(root, answers, stableJson(intake), { document: false, overwrite: false, mode: 384 });
188856
189573
  consumed = true;
188857
189574
  send(200, { saved: true, path: answers });
188858
- 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." });
188859
189576
  } catch (e) {
188860
189577
  busy = false;
188861
189578
  send(400, { error: e.message.slice(0, 300) });
@@ -188875,7 +189592,7 @@ async function serveOnboarding(options) {
188875
189592
  process.once("SIGINT", stop);
188876
189593
  process.once("SIGTERM", stop);
188877
189594
  try {
188878
- options.onReady?.({ url: `${origin}${prefix}/`, answers: join12(root, answers) });
189595
+ options.onReady?.({ url: `${origin}${prefix}/`, answers: join13(root, answers) });
188879
189596
  return await done;
188880
189597
  } finally {
188881
189598
  clearTimeout(timer);
@@ -188895,10 +189612,10 @@ async function onboardingStatus(options) {
188895
189612
  }
188896
189613
 
188897
189614
  // packages/cli/src/brain.ts
188898
- var object8 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
189615
+ var object9 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
188899
189616
  var integer = (value, min = 0) => Number.isSafeInteger(value) && Number(value) >= min;
188900
189617
  var text9 = (value, max) => typeof value === "string" && !!value.trim() && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
188901
- 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);
188902
189619
  var date = (value) => text9(value, 64) && Number.isFinite(Date.parse(value));
188903
189620
  function invalidInput(message) {
188904
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.");
@@ -188912,10 +189629,10 @@ function brainRevision(value) {
188912
189629
  return Number(value);
188913
189630
  }
188914
189631
  function validateInput(input, accept = false) {
188915
- if (!object8(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.");
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.");
188916
189633
  brandId(input.brandId);
188917
189634
  if (!integer(input.expectedDesignRevision, 1)) throw invalidInput("A positive source design revision is required.");
188918
- 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.");
188919
189636
  }
188920
189637
  function invalidResponse(write) {
188921
189638
  return new CliError(
@@ -188930,19 +189647,19 @@ function brainState(value, brand, write = false) {
188930
189647
  const invalid7 = () => {
188931
189648
  throw invalidResponse(write);
188932
189649
  };
188933
- if (!object8(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();
188934
189651
  let run = null;
188935
189652
  if (value.run !== null) {
188936
189653
  const row = value.run;
188937
- if (!object8(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();
188938
189655
  if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid7();
188939
189656
  let proposal = null;
188940
189657
  if (row.proposal !== null) {
188941
189658
  const proposed = row.proposal;
188942
- if (!object8(proposed) || !text9(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid7();
189659
+ if (!object9(proposed) || !text9(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid7();
188943
189660
  const recommendations = [];
188944
189661
  for (const item of proposed.recommendations) {
188945
- if (!object8(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text9(item.text, 500) || !text9(item.reason, 500) || !Array.isArray(item.sourceFields) || item.sourceFields.length < 1 || item.sourceFields.length > 5 || new Set(item.sourceFields).size !== item.sourceFields.length || item.sourceFields.some((field) => !text9(field, 400))) return invalid7();
189662
+ if (!object9(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text9(item.text, 500) || !text9(item.reason, 500) || !Array.isArray(item.sourceFields) || item.sourceFields.length < 1 || item.sourceFields.length > 5 || new Set(item.sourceFields).size !== item.sourceFields.length || item.sourceFields.some((field) => !text9(field, 400))) return invalid7();
188946
189663
  recommendations.push({ area: item.area, text: item.text, reason: item.reason, sourceFields: [...item.sourceFields] });
188947
189664
  }
188948
189665
  proposal = { summary: proposed.summary, recommendations };
@@ -188951,7 +189668,7 @@ function brainState(value, brand, write = false) {
188951
189668
  let usage = null;
188952
189669
  if (row.usage !== null) {
188953
189670
  const measured = row.usage;
188954
- if (!object8(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid7();
189671
+ if (!object9(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid7();
188955
189672
  usage = { inputTokens: measured.inputTokens, outputTokens: measured.outputTokens, totalTokens: measured.totalTokens, durationMs: measured.durationMs };
188956
189673
  }
188957
189674
  run = { id: row.id, status: row.status, proposal, usage, errorCode: row.errorCode, sourceDesignRevision: row.sourceDesignRevision, acceptedDesignRevision: row.acceptedDesignRevision, createdAt: row.createdAt, updatedAt: row.updatedAt };
@@ -189170,10 +189887,10 @@ async function loginWithDevice(options, overrides = {}) {
189170
189887
  }
189171
189888
 
189172
189889
  // packages/cli/src/index.ts
189173
- import { chmod as chmod2, lstat as lstat14, mkdir as mkdir14, open as open12 } from "node:fs/promises";
189174
- import { constants as constants11 } 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";
189175
189892
  import { homedir as homedir3 } from "node:os";
189176
- 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";
189177
189894
 
189178
189895
  // packages/cli/src/direction-context.ts
189179
189896
  async function prepareDirectionContext(root, client, projectId) {
@@ -189200,14 +189917,14 @@ async function prepareDirectionContext(root, client, projectId) {
189200
189917
  function invalid3() {
189201
189918
  throw new CliError("AUDIO_PROFILE_INVALID", "Invalid audio check profile.", "Use explicit numeric loudness targets and bounded runtime limits.");
189202
189919
  }
189203
- function object9(value, keys2) {
189920
+ function object10(value, keys2) {
189204
189921
  if (!value || typeof value !== "object" || Array.isArray(value)) invalid3();
189205
189922
  const result2 = value;
189206
189923
  if (Object.keys(result2).some((key) => !keys2.includes(key))) invalid3();
189207
189924
  return result2;
189208
189925
  }
189209
189926
  function validateAudioCheckProfile(value) {
189210
- const input = object9(value, ["schemaVersion", "loudness", "limits"]);
189927
+ const input = object10(value, ["schemaVersion", "loudness", "limits"]);
189211
189928
  if (input.schemaVersion !== 1) invalid3();
189212
189929
  let loudness;
189213
189930
  try {
@@ -189215,7 +189932,7 @@ function validateAudioCheckProfile(value) {
189215
189932
  } catch {
189216
189933
  invalid3();
189217
189934
  }
189218
- const limits = input.limits === void 0 ? {} : object9(input.limits, ["timeoutMs", "maxOutputBytes"]);
189935
+ const limits = input.limits === void 0 ? {} : object10(input.limits, ["timeoutMs", "maxOutputBytes"]);
189219
189936
  const timeoutMs = limits.timeoutMs === void 0 ? 6e5 : limits.timeoutMs;
189220
189937
  const maxOutputBytes = limits.maxOutputBytes === void 0 ? 4 * 1024 * 1024 : limits.maxOutputBytes;
189221
189938
  if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5 || typeof maxOutputBytes !== "number" || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1024 || maxOutputBytes > 16 * 1024 * 1024) invalid3();
@@ -189347,8 +190064,8 @@ var record12 = (value) => value !== null && typeof value === "object" && !Array.
189347
190064
  var array2 = (value) => Array.isArray(value) ? value : [];
189348
190065
  function plain(value, max = 2e3) {
189349
190066
  if (typeof value !== "string" || value.length > 16e3) return null;
189350
- const text12 = value.replace(/<[^>]*>/g, " ").replace(/&#(x[0-9a-f]+|[0-9]+);/gi, (_, number2) => {
189351
- 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);
189352
190069
  return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
189353
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();
189354
190071
  return text12 ? text12.slice(0, max) : null;
@@ -189670,9 +190387,9 @@ async function searchMediaSources(options, dependencies = {}) {
189670
190387
  }
189671
190388
 
189672
190389
  // packages/cli/src/media-inventory.ts
189673
- import { createHash as createHash12 } from "node:crypto";
189674
- import { link as link5, lstat as lstat11, mkdir as mkdir10, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm4 } from "node:fs/promises";
189675
- 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";
189676
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__"]);
189677
190394
  function mediaFailure(error) {
189678
190395
  if (error instanceof MediaToolError) return { code: error.code, message: error.message };
@@ -189698,7 +190415,7 @@ async function inventoryMedia(options) {
189698
190415
  }
189699
190416
  report.scannedEntries++;
189700
190417
  try {
189701
- const stat = await lstat11(path);
190418
+ const stat = await lstat14(path);
189702
190419
  if (stat.isSymbolicLink()) {
189703
190420
  if (explicit) throw new MediaToolError("MEDIA_SYMLINK", "Symlink inputs are not followed. Use the original local path.");
189704
190421
  skip(path, "symlink_not_followed");
@@ -189724,7 +190441,7 @@ async function inventoryMedia(options) {
189724
190441
  skip(path, "remaining_entries_not_scanned", true);
189725
190442
  break;
189726
190443
  }
189727
- await visit(join13(path, entry.name), depth + 1);
190444
+ await visit(join14(path, entry.name), depth + 1);
189728
190445
  }
189729
190446
  } else if (!stat.isFile()) {
189730
190447
  if (explicit) throw new MediaToolError("MEDIA_NOT_REGULAR", "The explicit media input must be a regular local file or directory.");
@@ -189759,23 +190476,23 @@ async function sampleMedia(options) {
189759
190476
  if (!source2.streams.some((stream) => stream.type === "video")) throw new MediaToolError("MEDIA_VIDEO_REQUIRED", "Frame sampling requires a video or image stream.");
189760
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.");
189761
190478
  const outputDirectory = resolveLocalMediaPath(options.outputDirectory);
189762
- await assertNoMediaSymlinks(dirname14(outputDirectory));
190479
+ await assertNoMediaSymlinks(dirname15(outputDirectory));
189763
190480
  try {
189764
- await mkdir10(outputDirectory);
190481
+ await mkdir11(outputDirectory);
189765
190482
  } catch (error) {
189766
190483
  if (error.code !== "EEXIST") throw error;
189767
190484
  }
189768
190485
  await assertNoMediaSymlinks(outputDirectory);
189769
- if (!(await lstat11(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
189770
- const temp = await mkdtemp3(join13(outputDirectory, ".editorbrain-samples-"));
189771
- const tempStat = await lstat11(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);
189772
190489
  const frames = [];
189773
190490
  const created = [];
189774
190491
  try {
189775
190492
  for (let index = 0; index < options.times.length; index++) {
189776
190493
  const time = options.times[index];
189777
190494
  const filename = `${source2.sha256.slice(0, 12)}-${String(index + 1).padStart(2, "0")}-${Math.round(time * 1e3)}ms.jpg`;
189778
- const temporary = join13(temp, filename), output2 = join13(outputDirectory, filename);
190495
+ const temporary = join14(temp, filename), output2 = join14(outputDirectory, filename);
189779
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 });
189780
190497
  const bytes = await readFile7(temporary);
189781
190498
  if (!bytes.length) throw new MediaToolError("MEDIA_SAMPLE_EMPTY", "The requested frame did not produce a usable image.");
@@ -189785,9 +190502,9 @@ async function sampleMedia(options) {
189785
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.");
189786
190503
  throw error;
189787
190504
  }
189788
- const outputStat = await lstat11(output2);
190505
+ const outputStat = await lstat14(output2);
189789
190506
  created.push({ path: output2, ino: outputStat.ino, dev: outputStat.dev, size: outputStat.size, mtimeMs: outputStat.mtimeMs, ctimeMs: outputStat.ctimeMs });
189790
- 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 });
189791
190508
  }
189792
190509
  const after = await probeLocalMedia(file);
189793
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.");
@@ -189796,7 +190513,7 @@ async function sampleMedia(options) {
189796
190513
  for (const file2 of created) {
189797
190514
  try {
189798
190515
  await assertNoMediaSymlinks(file2.path);
189799
- const current2 = await lstat11(file2.path);
190516
+ const current2 = await lstat14(file2.path);
189800
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 });
189801
190518
  } catch {
189802
190519
  }
@@ -189805,7 +190522,7 @@ async function sampleMedia(options) {
189805
190522
  } finally {
189806
190523
  try {
189807
190524
  await assertNoMediaSymlinks(temp);
189808
- const current2 = await lstat11(temp);
190525
+ const current2 = await lstat14(temp);
189809
190526
  if (current2.ino === tempStat.ino && current2.dev === tempStat.dev) await rm4(temp, { recursive: true, force: true });
189810
190527
  } catch {
189811
190528
  }
@@ -189817,22 +190534,22 @@ import { resolve as resolve8 } from "node:path";
189817
190534
  function invalidProfile(message) {
189818
190535
  throw new CliError("RENDER_PROFILE_INVALID", message, "Use a schemaVersion: 1 render profile with explicit technical requirements.");
189819
190536
  }
189820
- function object10(value, path, keys2) {
190537
+ function object11(value, path, keys2) {
189821
190538
  if (!value || typeof value !== "object" || Array.isArray(value)) invalidProfile(`${path} must be an object.`);
189822
190539
  const result2 = value;
189823
190540
  for (const key of Object.keys(result2)) if (!keys2.includes(key)) invalidProfile(`${path} contains unsupported field ${key}.`);
189824
190541
  return result2;
189825
190542
  }
189826
190543
  function validateRenderCheckProfile(value) {
189827
- const root = object10(value, "profile", ["schemaVersion", "expected", "tolerance", "audio", "silence", "black", "peak", "limits"]);
190544
+ const root = object11(value, "profile", ["schemaVersion", "expected", "tolerance", "audio", "silence", "black", "peak", "limits"]);
189828
190545
  if (root.schemaVersion !== 1) invalidProfile("profile.schemaVersion must be 1.");
189829
- const expected = root.expected === void 0 ? {} : object10(root.expected, "expected", ["width", "height", "fps", "durationSeconds"]);
189830
- const tolerance = root.tolerance === void 0 ? {} : object10(root.tolerance, "tolerance", ["fps", "durationSeconds"]);
189831
- const silence = root.silence === void 0 ? {} : object10(root.silence, "silence", ["enabled", "minDurationSeconds", "thresholdDb"]);
189832
- const black = root.black === void 0 ? {} : object10(root.black, "black", ["enabled", "minDurationSeconds", "pixelThreshold", "pictureBlackRatio"]);
189833
- const peak = root.peak === void 0 ? {} : object10(root.peak, "peak", ["enabled", "thresholdDbFS"]);
189834
- const limits = root.limits === void 0 ? {} : object10(root.limits, "limits", ["timeoutMs", "maxOutputBytes"]);
189835
- const number2 = (v, name, min, max, fallback, integer2 = false) => {
190546
+ const expected = root.expected === void 0 ? {} : object11(root.expected, "expected", ["width", "height", "fps", "durationSeconds"]);
190547
+ const tolerance = root.tolerance === void 0 ? {} : object11(root.tolerance, "tolerance", ["fps", "durationSeconds"]);
190548
+ const silence = root.silence === void 0 ? {} : object11(root.silence, "silence", ["enabled", "minDurationSeconds", "thresholdDb"]);
190549
+ const black = root.black === void 0 ? {} : object11(root.black, "black", ["enabled", "minDurationSeconds", "pixelThreshold", "pictureBlackRatio"]);
190550
+ const peak = root.peak === void 0 ? {} : object11(root.peak, "peak", ["enabled", "thresholdDbFS"]);
190551
+ const limits = root.limits === void 0 ? {} : object11(root.limits, "limits", ["timeoutMs", "maxOutputBytes"]);
190552
+ const number3 = (v, name, min, max, fallback, integer2 = false) => {
189836
190553
  if (v === void 0 && fallback !== void 0) return fallback;
189837
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}.`);
189838
190555
  return v;
@@ -189844,18 +190561,18 @@ function validateRenderCheckProfile(value) {
189844
190561
  };
189845
190562
  if (root.audio !== void 0 && !["required", "optional", "forbidden"].includes(root.audio)) invalidProfile("audio must be required, optional or forbidden.");
189846
190563
  const validatedExpected = {};
189847
- for (const key of ["width", "height"]) if (expected[key] !== void 0) validatedExpected[key] = number2(expected[key], `expected.${key}`, 1, 32768, void 0, true);
189848
- if (expected.fps !== void 0) validatedExpected.fps = number2(expected.fps, "expected.fps", 1e-6, 1e3);
189849
- 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);
189850
190567
  return {
189851
190568
  schemaVersion: 1,
189852
190569
  expected: validatedExpected,
189853
- 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) },
189854
190571
  audio: root.audio ?? "optional",
189855
- 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) },
189856
- 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) },
189857
- peak: { enabled: enabled(peak.enabled, "peak.enabled"), thresholdDbFS: number2(peak.thresholdDbFS, "peak.thresholdDbFS", -150, 0, -0.1) },
189858
- 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) }
189859
190576
  };
189860
190577
  }
189861
190578
  function errorCode(error) {
@@ -190077,10 +190794,10 @@ async function checkRender(options) {
190077
190794
  }
190078
190795
 
190079
190796
  // packages/cli/src/motion-components.ts
190080
- import { createHash as createHash13 } from "node:crypto";
190081
- import { constants as constants10 } from "node:fs";
190082
- import { lstat as lstat12, mkdir as mkdir11, open as open11, rmdir as rmdir2, unlink as unlink9 } from "node:fs/promises";
190083
- 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";
190084
190801
 
190085
190802
  // packages/core/src/motion-editorial.ts
190086
190803
  function createEditorialRenderer(config2, g) {
@@ -191567,9 +192284,9 @@ function motionDocumentBoot(config2) {
191567
192284
  }
191568
192285
  config2.items.forEach((item, index) => {
191569
192286
  const pos = layout.overview[index];
191570
- const object13 = element("div", "sticker-object", world);
191571
- stickerObjects.push(object13);
191572
- box(object13, pos.x - pos.size / 2, pos.y - pos.size / 2, pos.size, pos.size);
192287
+ const object14 = element("div", "sticker-object", world);
192288
+ stickerObjects.push(object14);
192289
+ box(object14, pos.x - pos.size / 2, pos.y - pos.size / 2, pos.size, pos.size);
191573
192290
  if (item.image) {
191574
192291
  const image2 = document.createElement("img");
191575
192292
  image2.src = item.image;
@@ -191578,7 +192295,7 @@ function motionDocumentBoot(config2) {
191578
192295
  image2.draggable = false;
191579
192296
  image2.dataset.stickerIndex = String(index);
191580
192297
  image2.style.visibility = "hidden";
191581
- object13.appendChild(image2);
192298
+ object14.appendChild(image2);
191582
192299
  images.push(image2);
191583
192300
  } else {
191584
192301
  const illustration = svgNode("svg", { viewBox: "-125 -125 250 250", class: "illustration", role: "img", "aria-label": "Illustration: " + item.label });
@@ -191586,7 +192303,7 @@ function motionDocumentBoot(config2) {
191586
192303
  illustration.appendChild(svgNode("path", { d: pathOf(contours[index]), fill: "none", stroke: "var(--fg)", "stroke-width": "1.4", "stroke-linejoin": "round" }));
191587
192304
  const glyph = svgNode("path", { d: index % 2 ? "M-24,0 L-6,18 L30,-22" : "M-28,0 H28 M0,-28 V28", fill: "none", stroke: "var(--fg)", "stroke-width": "6", "stroke-linecap": "round", "stroke-linejoin": "round" });
191588
192305
  illustration.appendChild(glyph);
191589
- object13.appendChild(illustration);
192306
+ object14.appendChild(illustration);
191590
192307
  }
191591
192308
  const overviewLabel = element("div", "overview-label measured", world, item.label);
191592
192309
  box(overviewLabel, pos.x - pos.labelWidth / 2, pos.y + pos.size / 2 + s * 0.02, pos.labelWidth, pos.labelHeight);
@@ -191661,9 +192378,9 @@ function motionDocumentBoot(config2) {
191661
192378
  const ca = cameraFor(a.index), cb = cameraFor(b.index), focus = lerp(ca.focus, cb.focus, blend);
191662
192379
  const x = lerp(ca.x, cb.x, blend), y = lerp(ca.y, cb.y, blend), z = lerp(ca.z, cb.z, blend);
191663
192380
  stickerPaint.clearRect(0, 0, W, H);
191664
- stickerObjects.forEach((object13, index) => {
192381
+ stickerObjects.forEach((object14, index) => {
191665
192382
  const pos = layout.overview[index];
191666
- box(object13, x + (pos.x - pos.size / 2) * z, y + (pos.y - pos.size / 2) * z, pos.size * z, pos.size * z);
192383
+ box(object14, x + (pos.x - pos.size / 2) * z, y + (pos.y - pos.size / 2) * z, pos.size * z, pos.size * z);
191667
192384
  });
191668
192385
  overviewLabels.forEach((node, index) => {
191669
192386
  const pos = layout.overview[index];
@@ -191892,18 +192609,18 @@ ${motionSceneLayout.toString()}
191892
192609
 
191893
192610
  // packages/cli/src/motion-components.ts
191894
192611
  var fail2 = (message) => new CliError("MOTION_COMPONENT_INVALID", message, "Use a pinned component, explicit resolved token bindings, a local WOFF2/TTF font and 2\u20134 plain-text items.");
191895
- function object11(value, name, allowed) {
192612
+ function object12(value, name, allowed) {
191896
192613
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !allowed.includes(key))) throw fail2(`${name} has invalid or unsupported fields.`);
191897
192614
  }
191898
192615
  function inputDocument(value) {
191899
- object11(value, "Input", ["componentId", "componentVersion", "bindings", "fontFile", "title", "subtitle", "duration", "items", "motion"]);
192616
+ object12(value, "Input", ["componentId", "componentVersion", "bindings", "fontFile", "title", "subtitle", "duration", "items", "motion"]);
191900
192617
  if (typeof value.componentId !== "string" || value.componentVersion !== "1.0.0" || !getMotionComponent(value.componentId, value.componentVersion)) throw fail2("Unknown component or unsupported pinned componentVersion.");
191901
- object11(value.bindings, "bindings", ["background", "foreground", "accent", "fontFamily"]);
192618
+ object12(value.bindings, "bindings", ["background", "foreground", "accent", "fontFamily"]);
191902
192619
  for (const role of ["background", "foreground", "accent", "fontFamily"]) if (typeof value.bindings[role] !== "string" || !/^[a-z][a-z0-9_.-]{0,79}$/.test(value.bindings[role])) throw fail2(`bindings.${role} must name an explicit semantic token key.`);
191903
192620
  if (typeof value.fontFile !== "string" || !value.fontFile) throw fail2("fontFile is required.");
191904
192621
  if (!Array.isArray(value.items) || value.items.length < 2 || value.items.length > 4) throw fail2("Input requires 2\u20134 items.");
191905
192622
  for (const item of value.items) {
191906
- object11(item, "item", ["label", "detail", "imageFile", "shape"]);
192623
+ object12(item, "item", ["label", "detail", "imageFile", "shape"]);
191907
192624
  if (item.imageFile !== void 0 && (typeof item.imageFile !== "string" || !item.imageFile)) throw fail2("imageFile must be an explicit local image path.");
191908
192625
  }
191909
192626
  return value;
@@ -191914,7 +192631,7 @@ function inputPath(base, value) {
191914
192631
  }
191915
192632
  async function sourceFile(path, role, max) {
191916
192633
  await assertNoMediaSymlinks(path);
191917
- const handle = await open11(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
192634
+ const handle = await open13(path, constants12.O_RDONLY | constants12.O_NOFOLLOW | constants12.O_NONBLOCK);
191918
192635
  try {
191919
192636
  const before = await handle.stat();
191920
192637
  if (!before.isFile() || before.size === 0 || before.size > max) throw fail2(`${role} must be a nonempty regular file of at most ${max} bytes.`);
@@ -191927,9 +192644,9 @@ async function sourceFile(path, role, max) {
191927
192644
  }
191928
192645
  const after = await handle.stat();
191929
192646
  await assertNoMediaSymlinks(path);
191930
- const current2 = await lstat12(path);
192647
+ const current2 = await lstat15(path);
191931
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.`);
191932
- 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 };
191933
192650
  } finally {
191934
192651
  await handle.close();
191935
192652
  }
@@ -191942,7 +192659,7 @@ function embed(content, path, kind2) {
191942
192659
  }
191943
192660
  async function exists2(path) {
191944
192661
  try {
191945
- await lstat12(path);
192662
+ await lstat15(path);
191946
192663
  return true;
191947
192664
  } catch (error) {
191948
192665
  if (error.code === "ENOENT") return false;
@@ -191955,22 +192672,22 @@ async function makeParents(root, path, created) {
191955
192672
  const relative2 = parts.slice(0, index).join("/");
191956
192673
  const target = await checkedPath(root, relative2, false);
191957
192674
  try {
191958
- await mkdir11(target, { mode: 448 });
191959
- const info = await lstat12(target);
192675
+ await mkdir12(target, { mode: 448 });
192676
+ const info = await lstat15(target);
191960
192677
  created.push({ path: relative2, dev: info.dev, ino: info.ino, directory: true });
191961
192678
  } catch (error) {
191962
192679
  if (error.code !== "EEXIST") throw error;
191963
- if (!(await lstat12(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.");
191964
192681
  }
191965
192682
  }
191966
192683
  }
191967
192684
  async function cleanCreated2(root, created) {
191968
192685
  for (const item of [...created].reverse()) {
191969
192686
  try {
191970
- const path = await checkedPath(root, item.path, false), info = await lstat12(path);
192687
+ const path = await checkedPath(root, item.path, false), info = await lstat15(path);
191971
192688
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
191972
192689
  if (item.directory) await rmdir2(path);
191973
- else await unlink9(path);
192690
+ else await unlink10(path);
191974
192691
  } catch {
191975
192692
  }
191976
192693
  }
@@ -191995,14 +192712,14 @@ async function prepareMotionComponent(options) {
191995
192712
  if (typeof value !== "string" || !value.trim()) throw fail2(`Required binding ${role} references missing or non-string token ${key}. No demo default was applied.`);
191996
192713
  return [role, value];
191997
192714
  }));
191998
- const fontPath = inputPath(dirname15(input.source.path), document2.fontFile);
192715
+ const fontPath = inputPath(dirname16(input.source.path), document2.fontFile);
191999
192716
  const font = await sourceFile(fontPath, "font", MOTION_INPUT_LIMITS.fontBytes);
192000
192717
  const sources = [input.source, font.source];
192001
192718
  const items = [];
192002
192719
  for (const [index, item] of document2.items.entries()) {
192003
192720
  let image2;
192004
192721
  if (item.imageFile) {
192005
- const path = inputPath(dirname15(input.source.path), item.imageFile);
192722
+ const path = inputPath(dirname16(input.source.path), item.imageFile);
192006
192723
  const file = await sourceFile(path, `items[${index}].image`, MOTION_INPUT_LIMITS.imageBytes);
192007
192724
  image2 = embed(file.content, path, "image");
192008
192725
  sources.push(file.source);
@@ -192043,7 +192760,7 @@ async function prepareMotionComponent(options) {
192043
192760
  resolvedBindings: Object.fromEntries(Object.entries(document2.bindings).map(([role, key]) => [role, { key, value: bound[role], source: resolved.tokenSources[key] }])),
192044
192761
  sources,
192045
192762
  context: { sourceHashes: resolved.lock.sourceHashes, output: resolved.output, mediaPreferences: resolved.mediaPreferences },
192046
- 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") } },
192047
192764
  warnings: resolved.warnings
192048
192765
  };
192049
192766
  const readme = `# EditorBrain motion component
@@ -192063,13 +192780,13 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
192063
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/.");
192064
192781
  const created = [];
192065
192782
  try {
192066
- await makeParents(root, dirname15(options.outDirectory), created);
192067
- await mkdir11(await productionOutputPath(root, options.outDirectory), { mode: 448 });
192068
- const info = await lstat12(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);
192069
192786
  created.push({ path: options.outDirectory, dev: info.dev, ino: info.ino, directory: true });
192070
192787
  for (const [name, content] of Object.entries(files)) {
192071
192788
  const path = `${options.outDirectory}/${name}`;
192072
- const handle = await open11(await productionOutputPath(root, path), constants10.O_WRONLY | constants10.O_CREAT | constants10.O_EXCL | constants10.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);
192073
192790
  try {
192074
192791
  const stat = await handle.stat();
192075
192792
  created.push({ path, dev: stat.dev, ino: stat.ino, directory: false });
@@ -192101,9 +192818,9 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
192101
192818
  }
192102
192819
 
192103
192820
  // packages/cli/src/production-verify.ts
192104
- import { createHash as createHash14, randomUUID as randomUUID6 } from "node:crypto";
192105
- import { mkdir as mkdir12, readFile as readFile8 } from "node:fs/promises";
192106
- 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";
192107
192824
 
192108
192825
  // packages/cli/src/production-media-review.ts
192109
192826
  function productionMediaReview(resolved) {
@@ -192160,7 +192877,7 @@ function productionEditorialReview(resolved) {
192160
192877
  }
192161
192878
 
192162
192879
  // packages/cli/src/production-verify.ts
192163
- var digest4 = (value) => createHash14("sha256").update(value).digest("hex");
192880
+ var digest4 = (value) => createHash16("sha256").update(value).digest("hex");
192164
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";
192165
192882
  function productionVerificationRequirements(options) {
192166
192883
  const { resolved } = options;
@@ -192194,7 +192911,7 @@ async function sampleFinalArtifact(file, probe2, directory, requested) {
192194
192911
  result2.failures.push({ requestedTimeSeconds: time, code: "MEDIA_SAMPLE_OUT_OF_RANGE" });
192195
192912
  continue;
192196
192913
  }
192197
- 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`);
192198
192915
  try {
192199
192916
  const output2 = await runMediaTool("ffmpeg", [
192200
192917
  "-loglevel",
@@ -192266,6 +192983,7 @@ function summarizeProductionVerification(report) {
192266
192983
  visualSheet: report.visualSheet,
192267
192984
  mediaReview: report.mediaReview,
192268
192985
  editorialReview: report.editorialReview,
192986
+ continuity: report.continuity,
192269
192987
  agentInstructions: report.agentInstructions,
192270
192988
  mediaUploaded: false,
192271
192989
  mediaModified: false,
@@ -192276,14 +192994,17 @@ async function verifyProduction(options) {
192276
192994
  const root = await ensureRoot(options.root);
192277
192995
  assertIdentifier(options.resolved.project.id);
192278
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);
192279
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.");
192280
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.");
192281
- 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()}`;
192282
193003
  const directory = await productionOutputPath(root, relativeDirectory);
192283
- await mkdir12(dirname16(directory), { recursive: true, mode: 448 });
193004
+ await mkdir13(dirname17(directory), { recursive: true, mode: 448 });
192284
193005
  await productionOutputPath(root, relativeDirectory);
192285
193006
  try {
192286
- await mkdir12(directory, { mode: 448 });
193007
+ await mkdir13(directory, { mode: 448 });
192287
193008
  } catch (error) {
192288
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/.");
192289
193010
  throw error;
@@ -192310,6 +193031,7 @@ async function verifyProduction(options) {
192310
193031
  visualSheet: null,
192311
193032
  mediaReview: productionMediaReview(options.resolved),
192312
193033
  editorialReview: productionEditorialReview(options.resolved),
193034
+ continuity: null,
192313
193035
  agentInstructions: [
192314
193036
  "Open the saved sample images and actual final file before making visual or audio claims. Samples have not been viewed automatically.",
192315
193037
  "Reconcile black, silence and peak candidates with the brief. A technical pass never approves storytelling, readability, music/SFX, fonts or synchronization.",
@@ -192338,9 +193060,13 @@ async function verifyProduction(options) {
192338
193060
  report.render = await checkRender({ file, profile: requirements.renderProfile });
192339
193061
  report.artifact = { ...report.render.file, stableAcrossVerification: null };
192340
193062
  const probe2 = report.render.measurements.probe;
192341
- if (requirements.loudness) {
193063
+ if (audioProfile.loudness || probe2?.streams.some((s) => s.type === "audio")) {
192342
193064
  report.audioMeasurement = "checked";
192343
- 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." });
192344
193070
  }
192345
193071
  if (probe2 && report.render.checks.find((check) => check.id === "decode")?.status === "pass") report.samples = await sampleFinalArtifact(file, probe2, directory, options.sampleTimesSeconds);
192346
193072
  if (probe2 && report.samples.status === "complete") {
@@ -192362,9 +193088,9 @@ async function verifyProduction(options) {
192362
193088
  }
192363
193089
  await contextCheck("validAtEnd");
192364
193090
  }
192365
- 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;
192366
193092
  const failed = report.issues.some((issue) => issue.severity === "error") || report.render?.technicalStatus === "fail" || report.audio?.technicalStatus === "fail";
192367
- 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";
192368
193094
  report.technicalPass = report.complete && !failed;
192369
193095
  const reportPath = await saveProductionReport(root, `${relativeDirectory}/report.json`, report);
192370
193096
  const reportSha256 = digest4(stableJson(report));
@@ -192372,12 +193098,12 @@ async function verifyProduction(options) {
192372
193098
  }
192373
193099
 
192374
193100
  // packages/cli/src/review-artifact.ts
192375
- import { lstat as lstat13, mkdir as mkdir13 } from "node:fs/promises";
192376
- import { basename as basename4, dirname as dirname17, extname as extname6, resolve as resolve11 } from "node:path";
192377
- 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";
192378
193104
 
192379
193105
  // packages/cli/src/review-artifact-html.ts
192380
- import { createHash as createHash15 } from "node:crypto";
193106
+ import { createHash as createHash17 } from "node:crypto";
192381
193107
  function reviewApp() {
192382
193108
  const data = JSON.parse(document.getElementById("review-data").textContent);
192383
193109
  const $ = (id3) => document.getElementById(id3);
@@ -192714,9 +193440,9 @@ ${JSON.stringify({ ...feedback(), kind: "editorbrain.review-access-request", dec
192714
193440
  update();
192715
193441
  }
192716
193442
  function renderReviewArtifact(data, wordmark) {
192717
- const script = `(${reviewApp.toString()})();`, hash8 = createHash15("sha256").update(script).digest("base64");
193443
+ const script = `(${reviewApp.toString()})();`, hash9 = createHash17("sha256").update(script).digest("base64");
192718
193444
  const json = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
192719
- 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>
192720
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}
192721
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}}
192722
193448
  @media(prefers-reduced-motion:no-preference){button,.direction{transition:background .15s,border-color .15s}}
@@ -192727,7 +193453,7 @@ function renderReviewArtifact(data, wordmark) {
192727
193453
  var invalid4 = (message) => {
192728
193454
  throw new CliError("INVALID_REVIEW_ARTIFACT", message, "See references/production-continuity.md. Use a new .editorbrain-local/.../review.html output for each version.");
192729
193455
  };
192730
- var object12 = (v, keys2) => {
193456
+ var object13 = (v, keys2) => {
192731
193457
  if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys2.includes(k))) invalid4("Unexpected artifact fields.");
192732
193458
  return v;
192733
193459
  };
@@ -192736,14 +193462,14 @@ function text10(v, max) {
192736
193462
  return v.trim();
192737
193463
  }
192738
193464
  function media2(v) {
192739
- const m = object12(v, ["file", "sha256"]);
193465
+ const m = object13(v, ["file", "sha256"]);
192740
193466
  const file = text10(m.file, 4096);
192741
193467
  if (/^[a-z]+:\/\//i.test(file)) invalid4("Use a local media file, never a remote or signed URL.");
192742
193468
  if (m.sha256 !== void 0 && (typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256))) invalid4("Invalid media hash.");
192743
193469
  return { file, ...m.sha256 ? { sha256: m.sha256 } : {} };
192744
193470
  }
192745
193471
  function parseReviewArtifact(value) {
192746
- const r = object12(value, ["schemaVersion", "projectId", "title", "version", "stage", "video", "transcript", "directions", "contextVersion", "learnings", "learningContext"]);
193472
+ const r = object13(value, ["schemaVersion", "projectId", "title", "version", "stage", "video", "transcript", "directions", "contextVersion", "learnings", "learningContext"]);
192747
193473
  if (r.schemaVersion !== 1 || !["directions", "review", "delivery"].includes(r.stage)) invalid4("Use schemaVersion 1 and stage directions, review or delivery.");
192748
193474
  const projectId = text10(r.projectId, 80);
192749
193475
  assertIdentifier(projectId);
@@ -192760,7 +193486,7 @@ function parseReviewArtifact(value) {
192760
193486
  }
192761
193487
  }
192762
193488
  if (r.learningContext !== void 0) {
192763
- const c = object12(r.learningContext, ["brandId", "styleId", "formatId", "seriesId"]);
193489
+ const c = object13(r.learningContext, ["brandId", "styleId", "formatId", "seriesId"]);
192764
193490
  assertIdentifier(text10(c.brandId, 80));
192765
193491
  assertIdentifier(text10(c.styleId, 80));
192766
193492
  if (memoryContextIssues({ ...c.formatId !== void 0 ? { formatId: c.formatId } : {}, ...c.seriesId !== void 0 ? { seriesId: c.seriesId } : {} }).length) invalid4("Invalid learning format or series.");
@@ -192779,7 +193505,7 @@ function parseReviewArtifact(value) {
192779
193505
  if (!Array.isArray(r.directions) || r.directions.length < 1 || r.directions.length > 3) invalid4("Use one to three visual directions.");
192780
193506
  const ids2 = /* @__PURE__ */ new Set();
192781
193507
  result2.directions = r.directions.map((v) => {
192782
- const d = object12(v, ["id", "title", "description", "preview", "references"]), id3 = text10(d.id, 80);
193508
+ const d = object13(v, ["id", "title", "description", "preview", "references"]), id3 = text10(d.id, 80);
192783
193509
  assertIdentifier(id3);
192784
193510
  if (ids2.has(id3)) invalid4("Direction IDs must be unique.");
192785
193511
  ids2.add(id3);
@@ -192787,7 +193513,7 @@ function parseReviewArtifact(value) {
192787
193513
  if (d.references !== void 0) {
192788
193514
  if (!Array.isArray(d.references) || d.references.length > 5) invalid4("Use up to five inspected reference links per direction.");
192789
193515
  references = d.references.map((v2) => {
192790
- const ref = object12(v2, ["label", "url"]), label = text10(ref.label, 140), url2 = text10(ref.url, 2e3);
193516
+ const ref = object13(v2, ["label", "url"]), label = text10(ref.label, 140), url2 = text10(ref.url, 2e3);
192791
193517
  let parsed;
192792
193518
  try {
192793
193519
  parsed = new URL(url2);
@@ -192810,7 +193536,7 @@ async function prepareMedia(root, input, kind2, mediaDir, entries) {
192810
193536
  const mime = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
192811
193537
  if (!mime[extension] || kind2 === "video" && !mime[extension].startsWith("video/")) invalid4("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
192812
193538
  const bytes = await readReviewFile(path, REVIEW_MEDIA_BYTES);
192813
- const sha2562 = createHash16("sha256").update(bytes).digest("hex");
193539
+ const sha2562 = createHash18("sha256").update(bytes).digest("hex");
192814
193540
  if (input.sha256 && input.sha256 !== sha2562) invalid4("Preview hash does not match this version.");
192815
193541
  if (!mediaDir) return { uri: `data:${mime[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime[extension] };
192816
193542
  const name = `${sha2562}${extension}`, file = `${mediaDir}/${name}`;
@@ -192828,7 +193554,7 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
192828
193554
  const target = await productionOutputPath(root, out);
192829
193555
  for (const path of [target, `${target}.review.json`]) {
192830
193556
  try {
192831
- await lstat13(path);
193557
+ await lstat16(path);
192832
193558
  } catch (error) {
192833
193559
  if (error.code === "ENOENT") continue;
192834
193560
  throw error;
@@ -192836,7 +193562,7 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
192836
193562
  invalid4("Review output already exists. Use a new filename; previous decisions are preserved.");
192837
193563
  }
192838
193564
  const entries = [];
192839
- const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID7()}` : void 0;
193565
+ const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID8()}` : void 0;
192840
193566
  const video = input.video ? await prepareMedia(root, input.video, "video", mediaDir, entries) : void 0;
192841
193567
  const directions = input.directions ? [] : void 0;
192842
193568
  for (const { preview, ...direction } of input.directions ?? []) {
@@ -192844,19 +193570,19 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
192844
193570
  }
192845
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 } : {} };
192846
193572
  if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid4("Embedded previews exceed 40 MiB. Use smaller review copies.");
192847
- const artifactId = createHash16("sha256").update(JSON.stringify(clean)).digest("hex");
193573
+ const artifactId = createHash18("sha256").update(JSON.stringify(clean)).digest("hex");
192848
193574
  const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
192849
- await mkdir13(dirname17(target), { recursive: true });
193575
+ await mkdir14(dirname18(target), { recursive: true });
192850
193576
  await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
192851
- 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 });
192852
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." };
192853
193579
  }
192854
193580
 
192855
193581
  // packages/cli/src/review-server.ts
192856
193582
  import { createServer as createServer2 } from "node:http";
192857
- import { createHash as createHash17, randomBytes as randomBytes2 } from "node:crypto";
193583
+ import { createHash as createHash19, randomBytes as randomBytes2 } from "node:crypto";
192858
193584
  import { basename as basename5 } from "node:path";
192859
- var hash6 = (bytes) => createHash17("sha256").update(bytes).digest("hex");
193585
+ var hash7 = (bytes) => createHash19("sha256").update(bytes).digest("hex");
192860
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.");
192861
193587
  var validHash = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
192862
193588
  async function startReviewArtifact(root, file, port = 0) {
@@ -192866,7 +193592,7 @@ async function startReviewArtifact(root, file, port = 0) {
192866
193592
  const manifest = JSON.parse((await readReviewFile(manifestPath, 64 * 1024)).toString());
192867
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();
192868
193594
  const html = await readReviewFile(await productionOutputPath(root, file), 2 * 1024 * 1024);
192869
- 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();
192870
193596
  const resources = /* @__PURE__ */ new Map();
192871
193597
  resources.set("index.html", { body: html, mime: "text/html; charset=utf-8" });
192872
193598
  const mime = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
@@ -192878,7 +193604,7 @@ async function startReviewArtifact(root, file, port = 0) {
192878
193604
  const uri = `${encodeURIComponent(basename5(file) + ".media-" + match[1])}/${match[2]}.${match[3]}`;
192879
193605
  if (entry.uri !== uri || resources.has(uri)) throw invalid5();
192880
193606
  const bytes = await readReviewFile(await productionOutputPath(root, entry.file), REVIEW_MEDIA_BYTES);
192881
- if (bytes.length !== entry.bytes || hash6(bytes) !== entry.sha256) throw invalid5();
193607
+ if (bytes.length !== entry.bytes || hash7(bytes) !== entry.sha256) throw invalid5();
192882
193608
  resources.set(uri, { body: bytes, mime: entry.mimeType });
192883
193609
  }
192884
193610
  const token = randomBytes2(24).toString("hex"), prefix = `/${token}/`;
@@ -192949,7 +193675,7 @@ async function startReviewArtifact(root, file, port = 0) {
192949
193675
  });
192950
193676
  try {
192951
193677
  const probe2 = await fetch(url2, { signal: AbortSignal.timeout(5e3) });
192952
- 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();
192953
193679
  } catch (error) {
192954
193680
  await close();
192955
193681
  throw error;
@@ -192975,7 +193701,7 @@ var uuid2 = (value, name) => {
192975
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.`);
192976
193702
  return value;
192977
193703
  };
192978
- var hash7 = (value, name) => {
193704
+ var hash8 = (value, name) => {
192979
193705
  if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid6(`${name} must be an exact SHA-256 hash.`);
192980
193706
  return value;
192981
193707
  };
@@ -192988,7 +193714,7 @@ function reviewBody(value, command) {
192988
193714
  const fields = command === "sample" ? ["assetId", "contextVersion", "title", "notes", "parentRevisionId", "revisionId", "transcript"] : ["resultRevisionId", "contextVersion", "resultNote", "preservedElements"];
192989
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.");
192990
193716
  const body = value;
192991
- hash7(body.contextVersion, "contextVersion");
193717
+ hash8(body.contextVersion, "contextVersion");
192992
193718
  if (command === "sample") {
192993
193719
  if (body.transcript !== void 0) {
192994
193720
  try {
@@ -192997,7 +193723,7 @@ function reviewBody(value, command) {
192997
193723
  invalid6(e.message);
192998
193724
  }
192999
193725
  }
193000
- hash7(body.assetId, "assetId");
193726
+ hash8(body.assetId, "assetId");
193001
193727
  text11(body.title, "title", 120);
193002
193728
  text11(body.notes, "notes", 2e3, true);
193003
193729
  for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0) uuid2(body[key], key);
@@ -193031,7 +193757,7 @@ async function productionReviewCommand(client, root, command, flags) {
193031
193757
  assertIdentifier(projectId);
193032
193758
  const base = `/v1/projects/${encodeURIComponent(projectId)}`;
193033
193759
  const revision2 = () => encodeURIComponent(uuid2(required("revision"), "--revision"));
193034
- const contextVersion = () => hash7(required("context-version"), "--context-version");
193760
+ const contextVersion = () => hash8(required("context-version"), "--context-version");
193035
193761
  const after = flags.after === void 0 ? void 0 : uuid2(required("after"), "--after");
193036
193762
  if (command === "transcript") return client.request(`${base}/production-reviews/${revision2()}/transcript`);
193037
193763
  if (command === "reviews") return client.request(`${base}/production-reviews${after ? "?" + new URLSearchParams({ after }) : ""}`);
@@ -193164,9 +193890,13 @@ editorbrain library media <video-id> --sha256 media-hash --out file
193164
193890
  editorbrain narrative search [query] [--kind hook|cta|...] [--channel visual|spoken|...] [--limit 10]
193165
193891
  editorbrain narrative get <video-id> [--sha256 document-hash] [--event-offset 0] [--relation-offset 0] [--limit 50]
193166
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]
193167
193897
  editorbrain styles source <id> --style-version <v> --out <archive> [--dir folder]
193168
193898
  editorbrain styles prepare <id> --style-version <v> --file <archive> --out <new-directory> [--dir folder]
193169
- 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]
193170
193900
  editorbrain styles push <style-id> [--with-resources] [--dry-run] [--dir folder]
193171
193901
  editorbrain styles pull <style-id> [--dry-run] [--dir folder]
193172
193902
  editorbrain styles test <style-id> --project project-id [--dir folder]
@@ -193175,7 +193905,7 @@ editorbrain styles component prepare --style ID --id ID --parameters params.json
193175
193905
  editorbrain styles component list --style ID [--dir folder]
193176
193906
  editorbrain media style create <style-id> --style <style-id> --file recipe.json [--dir folder]
193177
193907
  editorbrain styles captions create --style ID --file captions.json [--dir folder]
193178
- editorbrain styles captions prepare --project 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]
193179
193909
  editorbrain styles techniques create --style ID --file techniques.json [--dir folder]
193180
193910
  editorbrain styles check <style-id> [--dir folder]
193181
193911
  editorbrain media styles [--category image|motion]
@@ -193200,7 +193930,7 @@ editorbrain production matte-check --file montage.mp4 --mask-file mask.mp4 [--di
193200
193930
  editorbrain production matte --engine apple-vision --file montage.mp4 --out .editorbrain-local/new-matte [--dir folder]
193201
193931
  editorbrain production matte-plan --file montage.mp4 [--dir folder]
193202
193932
  editorbrain production check --file render [--profile local-profile.json] [--dir folder] [--out .editorbrain-local/report.json] [--details]
193203
- 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]
193204
193934
  editorbrain production review-artifact --file review.json --out .editorbrain-local/review-v1.html [--media-mode local|embedded] [--dir folder]
193205
193935
  editorbrain production review-open --file .editorbrain-local/review-v1.html [--port 0] [--dir folder]
193206
193936
  editorbrain production reviews --project ID [--after UUID]
@@ -193247,8 +193977,8 @@ function parseArgs(argv) {
193247
193977
  const positional = [];
193248
193978
  const flags = {};
193249
193979
  const motionFilters = /* @__PURE__ */ new Map();
193250
- 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"]);
193251
- 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]);
193252
193982
  known.add("material");
193253
193983
  known.add("funcion");
193254
193984
  known.add("encuadre");
@@ -193301,16 +194031,16 @@ function output(value) {
193301
194031
  process.stdout.write(stableJson(value));
193302
194032
  }
193303
194033
  async function configRoot(create = false) {
193304
- 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");
193305
194035
  if (!create && !process.env.EDITORBRAIN_CONFIG_DIR && !process.env.EDITORHARNESS_CONFIG_DIR) {
193306
194036
  try {
193307
- await lstat14(path);
194037
+ await lstat17(path);
193308
194038
  } catch (error) {
193309
194039
  if (error.code !== "ENOENT") throw error;
193310
- path = join15(homedir3(), ".config", "editorharness");
194040
+ path = join16(homedir3(), ".config", "editorharness");
193311
194041
  }
193312
194042
  }
193313
- if (create) await mkdir14(path, { recursive: true, mode: 448 });
194043
+ if (create) await mkdir15(path, { recursive: true, mode: 448 });
193314
194044
  return ensureRoot(path);
193315
194045
  }
193316
194046
  async function loadConfig() {
@@ -193327,7 +194057,7 @@ async function loadConfig() {
193327
194057
  async function saveConfig(config2) {
193328
194058
  const root = await configRoot(true);
193329
194059
  await atomicWrite(root, "config.json", stableJson(config2), { document: false, mode: 384 });
193330
- await chmod2(join15(root, "config.json"), 384);
194060
+ await chmod3(join16(root, "config.json"), 384);
193331
194061
  }
193332
194062
  async function config(args, requireKey = true) {
193333
194063
  const stored = await loadConfig();
@@ -193356,7 +194086,7 @@ async function init(args) {
193356
194086
  for (const path of Object.keys(files)) {
193357
194087
  const target = await checkedPath(root, path);
193358
194088
  try {
193359
- await lstat14(target);
194089
+ await lstat17(target);
193360
194090
  throw new Error(`Refusing to replace existing file: ${path}`);
193361
194091
  } catch (error) {
193362
194092
  if (error.code !== "ENOENT") throw error;
@@ -193368,13 +194098,13 @@ async function init(args) {
193368
194098
  for (const path of directories) {
193369
194099
  const target = await checkedPath(root, path, false);
193370
194100
  try {
193371
- if (!(await lstat14(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
194101
+ if (!(await lstat17(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
193372
194102
  } catch (error) {
193373
194103
  if (error.code !== "ENOENT") throw error;
193374
194104
  }
193375
194105
  }
193376
194106
  for (const [path, content] of Object.entries(files)) await atomicWrite(root, path, content, { overwrite: false });
193377
- 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 });
193378
194108
  const guidance2 = await installGuidance();
193379
194109
  try {
193380
194110
  await rememberGuidance(guidance2);
@@ -193433,10 +194163,10 @@ async function main() {
193433
194163
  output({ name: "EditorBrain", version: await cliVersion() });
193434
194164
  return;
193435
194165
  }
193436
- if (args.flags["dry-run"] && !["push", "pull", "update"].includes(command) && !(command === "onboarding" && ["apply", "sync"].includes(subcommand))) throw new CliError("INVALID_ARGUMENT", "--dry-run is supported by push, pull, update and onboarding apply/sync.", "Read editorbrain help.");
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.");
193437
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.");
193438
194168
  if (!command || command === "help" || args.flags.help) {
193439
- process.stdout.write(HELP);
194169
+ process.stdout.write(commandHelp(HELP, command === "help" ? args.positional.slice(1) : args.flags.help ? args.positional : []));
193440
194170
  return;
193441
194171
  }
193442
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.");
@@ -193708,7 +194438,7 @@ async function main() {
193708
194438
  if (hookEnd !== void 0 && (!hookEnd.trim() || !Number.isFinite(Number(hookEnd)) || Number(hookEnd) < 0)) throw new Error("--hook-end must be nonnegative final seconds.");
193709
194439
  const credentials = projectId && !args.flags.offline ? await config(args, false) : void 0;
193710
194440
  const context = projectId ? await prepareProductionContext(root2, projectId, credentials?.apiKey ? new Client(credentials) : void 0) : void 0;
193711
- 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) }));
193712
194442
  return;
193713
194443
  }
193714
194444
  if (command === "production" && ["review-sheet", "matte", "matte-plan", "matte-engines", "matte-check"].includes(subcommand)) {
@@ -193735,7 +194465,7 @@ async function main() {
193735
194465
  }
193736
194466
  if (command === "production" && subcommand === "verify") {
193737
194467
  if (argument) throw new CliError("INVALID_ARGUMENT", "Use named flags for production verify.", "Read editorbrain help.");
193738
- 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"]);
193739
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.");
193740
194470
  const projectId = str(args, "project"), file = str(args, "file");
193741
194471
  if (!projectId || !file) throw new CliError("INVALID_ARGUMENT", "--project and --file are required.", "Read editorbrain help.");
@@ -193749,7 +194479,7 @@ async function main() {
193749
194479
  const client = credentials?.apiKey ? new Client(credentials) : void 0;
193750
194480
  await withWorkspaceLock(root2, async () => {
193751
194481
  const context = await prepareProductionContext(root2, projectId, client);
193752
- 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) } : {} });
193753
194483
  output({ ...args.flags.details ? result2.report : result2.summary, contextScope: context.contextScope, reportPath: result2.reportPath, reportSha256: result2.reportSha256 });
193754
194484
  if (result2.report.technicalStatus === "fail") process.exitCode = 1;
193755
194485
  else if (!result2.report.complete) process.exitCode = 2;
@@ -193925,9 +194655,9 @@ async function main() {
193925
194655
  throw new Error("Use styles component extract --style ID --id ID --scene scene.html [--bindings file.json], or prepare --parameters file.json --out new.html");
193926
194656
  }
193927
194657
  if (subcommand === "captions" && argument === "prepare") {
193928
- valid(3, ["project", "file", "out"]);
193929
- if (!str(args, "project") || !str(args, "file") || !str(args, "out")) throw new Error("Use styles captions prepare --project ID --file cues.json --out new.html");
193930
- output(await prepareCaptions(directory, str(args, "project"), str(args, "file"), str(args, "out")));
194658
+ valid(3, ["project", "style", "file", "out"]);
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");
194660
+ output(await prepareCaptions(directory, str(args, "project"), str(args, "file"), str(args, "out"), str(args, "style")));
193931
194661
  return;
193932
194662
  }
193933
194663
  valid(command === "media" ? 4 : 3, ["style", "file"]);
@@ -193936,13 +194666,29 @@ async function main() {
193936
194666
  output(await saveStyleContract(directory, id3, command === "media" ? "media-style.json" : subcommand === "captions" ? "captions.json" : "techniques.json", file));
193937
194667
  return;
193938
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
+ }
193939
194685
  if (command === "styles" && (subcommand === "create" || subcommand === "check")) {
193940
- const allowed = new Set(subcommand === "create" ? ["dir", "name", "from-project"] : ["dir"]);
194686
+ const allowed = new Set(subcommand === "create" ? ["dir", "name", "from-project", "scene"] : ["dir"]);
193941
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))) {
193942
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.");
193943
194689
  }
193944
194690
  const options = { directory: str(args, "dir") ?? process.cwd(), id: argument ?? `${str(args, "from-project")}-style` };
193945
- 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") }));
193946
194692
  else {
193947
194693
  const result2 = await checkLocalStyle(options);
193948
194694
  output(result2);
@@ -193978,7 +194724,7 @@ async function main() {
193978
194724
  const outRoot = await ensureRoot(resolve12(str(args, "dir") ?? process.cwd(), destination), true);
193979
194725
  for (const path of Object.keys(result2.files)) {
193980
194726
  try {
193981
- await lstat14(await checkedPath(outRoot, path, false));
194727
+ await lstat17(await checkedPath(outRoot, path, false));
193982
194728
  throw new Error(`Refusing to replace existing proposal: ${path}`);
193983
194729
  } catch (error) {
193984
194730
  if (error.code !== "ENOENT") throw error;
@@ -194004,7 +194750,7 @@ async function main() {
194004
194750
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(result2.id) || typeof result2.apiKey !== "string") throw new Error("Invalid key response");
194005
194751
  const file = `keys/${result2.id}.json`;
194006
194752
  await atomicWrite(root2, file, stableJson({ url: client.url, apiKey: result2.apiKey, id: result2.id, label, role }), { document: false, mode: 384, overwrite: false });
194007
- output({ id: result2.id, label, role, credentialFile: join15(root2, file) });
194753
+ output({ id: result2.id, label, role, credentialFile: join16(root2, file) });
194008
194754
  return;
194009
194755
  }
194010
194756
  if (subcommand === "revoke" && argument) {
@@ -194135,7 +194881,7 @@ async function main() {
194135
194881
  }
194136
194882
  if (subcommand === "upload" && argument) {
194137
194883
  const target = resolve12(str(args, "dir") ?? process.cwd(), argument);
194138
- const handle = await open12(target, constants11.O_RDONLY | constants11.O_NOFOLLOW);
194884
+ const handle = await open14(target, constants13.O_RDONLY | constants13.O_NOFOLLOW);
194139
194885
  let bytes;
194140
194886
  try {
194141
194887
  const info = await handle.stat();
@@ -194147,22 +194893,22 @@ async function main() {
194147
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" };
194148
194894
  const mimeType = str(args, "mime") ?? types2[extname7(target).toLowerCase()];
194149
194895
  if (!mimeType) throw new Error("Unsupported extension; specify --mime for a supported media format");
194150
- const hash8 = await sha256(bytes);
194896
+ const hash9 = await sha256(bytes);
194151
194897
  const params = new URLSearchParams({ name: basename6(target) });
194152
194898
  if (str(args, "project")) params.set("projectId", str(args, "project"));
194153
194899
  if (str(args, "purpose")) params.set("purpose", str(args, "purpose"));
194154
194900
  if (str(args, "source-sha256")) params.set("sourceSha256", str(args, "source-sha256"));
194155
- const path = `/v1/assets/${hash8}?${params}`;
194901
+ const path = `/v1/assets/${hash9}?${params}`;
194156
194902
  const result2 = str(args, "purpose") === "preview" ? await client.uploadPreview(path, bytes, mimeType) : await client.media(path, { content: bytes, mimeType });
194157
194903
  const body = await result2.json();
194158
- if (body.sha256 !== hash8) throw new Error("Upload response hash mismatch");
194904
+ if (body.sha256 !== hash9) throw new Error("Upload response hash mismatch");
194159
194905
  output(body);
194160
194906
  return;
194161
194907
  }
194162
194908
  if (subcommand === "download" && argument && str(args, "out")) {
194163
194909
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
194164
194910
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
194165
- const root2 = await ensureRoot(dirname18(destination), true);
194911
+ const root2 = await ensureRoot(dirname19(destination), true);
194166
194912
  await checkedPath(root2, basename6(destination), false);
194167
194913
  const response = await client.media(`/v1/assets/${argument}`);
194168
194914
  const bytes = new Uint8Array(await response.arrayBuffer());
@@ -194223,7 +194969,7 @@ async function main() {
194223
194969
  if (command === "search" && subcommand === "brief") {
194224
194970
  const path = str(args, "file");
194225
194971
  if (!path) throw new Error("Provide --file with the editorial brief JSON after inspecting the actual material.");
194226
- const handle = await open12(resolve12(path), constants11.O_RDONLY | constants11.O_NOFOLLOW);
194972
+ const handle = await open14(resolve12(path), constants13.O_RDONLY | constants13.O_NOFOLLOW);
194227
194973
  let brief;
194228
194974
  try {
194229
194975
  const stat = await handle.stat();
@@ -194245,7 +194991,7 @@ async function main() {
194245
194991
  const scriptPath = str(args, "script"), videoPath = str(args, "video");
194246
194992
  let script, assetId = str(args, "asset");
194247
194993
  const readInput = async (path, max) => {
194248
- const handle = await open12(resolve12(path), constants11.O_RDONLY | constants11.O_NOFOLLOW);
194994
+ const handle = await open14(resolve12(path), constants13.O_RDONLY | constants13.O_NOFOLLOW);
194249
194995
  try {
194250
194996
  const stat = await handle.stat();
194251
194997
  if (!stat.isFile() || stat.size < 1 || stat.size > max) throw new Error(`Input must be a regular file of at most ${max} bytes.`);
@@ -194301,20 +195047,20 @@ async function main() {
194301
195047
  }
194302
195048
  if (subcommand === "get" && argument) {
194303
195049
  const document2 = str(args, "document");
194304
- const hash8 = str(args, "sha256");
194305
- if (hash8 && !document2) throw new Error("--sha256 requires --document for library get.");
194306
- const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash8 ? { sha256: hash8 } : {} })}` : ""}`);
194307
- 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.");
194308
195054
  output(result2);
194309
195055
  return;
194310
195056
  }
194311
195057
  if (subcommand === "media" && argument && str(args, "out")) {
194312
- const hash8 = str(args, "sha256");
194313
- 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.");
194314
195060
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
194315
- const root2 = await ensureRoot(dirname18(destination), true);
195061
+ const root2 = await ensureRoot(dirname19(destination), true);
194316
195062
  await checkedPath(root2, basename6(destination), false);
194317
- const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash8}`);
195063
+ const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash9}`);
194318
195064
  const reader = response.body?.getReader();
194319
195065
  if (!reader) throw new Error("Media body missing.");
194320
195066
  const chunks = [];
@@ -194330,9 +195076,9 @@ async function main() {
194330
195076
  chunks.push(value);
194331
195077
  }
194332
195078
  const bytes = Buffer.concat(chunks);
194333
- 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.");
194334
195080
  await atomicWrite(root2, basename6(destination), bytes, { document: false, overwrite: false });
194335
- 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 });
194336
195082
  return;
194337
195083
  }
194338
195084
  throw new Error("Use library search, library get, or library media <video-id> --sha256 hash --out file.");