editorbrain 0.48.0 → 0.49.1

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.
@@ -163,8 +163,8 @@ function validateStyleRules(value) {
163
163
  const rules = Array.from(doc.rules, (input2) => {
164
164
  if (!input2 || typeof input2 !== "object") invalid("expected rule.");
165
165
  const type = input2.check;
166
- const fields2 = type === "frame.content" ? ["timeSeconds", "content", "text"] : type === "text.forbidden" ? ["phrases", "caseSensitive"] : type === "layout.safeZone" ? ["insets", "text"] : type === "audio.loudness" ? ["target"] : type === "manual" ? ["instruction"] : invalid("unsupported rule type.");
167
- const rule = object(input2, ["id", "check", "strength", "origin", ...fields2]);
166
+ const fields3 = type === "frame.content" ? ["timeSeconds", "content", "text"] : type === "text.forbidden" ? ["phrases", "caseSensitive"] : type === "layout.safeZone" ? ["insets", "text"] : type === "audio.loudness" ? ["target"] : type === "manual" ? ["instruction"] : invalid("unsupported rule type.");
167
+ const rule = object(input2, ["id", "check", "strength", "origin", ...fields3]);
168
168
  const ruleId = identifier(rule.id);
169
169
  if (ids2.has(ruleId)) invalid("duplicate rule id.");
170
170
  ids2.add(ruleId);
@@ -265,8 +265,8 @@ var forbiddenText = /(?:\b[a-z][a-z0-9+.-]*:\/\/|\b(?:data|file|mailto):|\b(?:au
265
265
  function safeStyleResourcePath(path) {
266
266
  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");
267
267
  const parts = path.split("/");
268
- const invalid13 = 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));
269
- if (invalid13.length) throw new Error(`Unsafe or nonportable resource path segment in ${JSON.stringify(path)}: ${invalid13.map((p) => JSON.stringify(p)).join(", ")}. Use relative segments of 1\u2013100 characters without traversal, reserved device names or trailing dots/spaces.`);
268
+ const invalid14 = 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));
269
+ if (invalid14.length) throw new Error(`Unsafe or nonportable resource path segment in ${JSON.stringify(path)}: ${invalid14.map((p) => JSON.stringify(p)).join(", ")}. Use relative segments of 1\u2013100 characters without traversal, reserved device names or trailing dots/spaces.`);
270
270
  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");
271
271
  return path;
272
272
  }
@@ -274,7 +274,7 @@ function validateStyleResources(value, expectedId) {
274
274
  const path = `.editorbrain/styles/${expectedId}/resources.json`;
275
275
  const issues = [];
276
276
  const add = (message) => issues.push({ path, message });
277
- const fields2 = (entry, allowed, label) => {
277
+ const fields3 = (entry, allowed, label) => {
278
278
  if (Object.keys(entry).some((key) => !allowed.includes(key))) add(`${label} has unsupported fields; do not include URLs, credentials or hidden resource sources`);
279
279
  };
280
280
  const text15 = (value2, label) => {
@@ -282,7 +282,7 @@ function validateStyleResources(value, expectedId) {
282
282
  else if (forbiddenText.test(value2) || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value2)) add(`${label} cannot contain URLs, credentials or control characters`);
283
283
  };
284
284
  if (!object2(value)) return { valid: false, issues: [{ path, message: "Style resources must be a JSON object" }] };
285
- fields2(value, ["schemaVersion", "id", "resources"], "Style resources");
285
+ fields3(value, ["schemaVersion", "id", "resources"], "Style resources");
286
286
  if (value.schemaVersion !== 1) add("schemaVersion must be 1");
287
287
  if (!identifier2.test(expectedId) || value.id !== expectedId) add(`Style resource id must match path: ${expectedId}`);
288
288
  if (!Array.isArray(value.resources) || value.resources.length > 200) add("Style resources requires a resources array");
@@ -294,7 +294,7 @@ function validateStyleResources(value, expectedId) {
294
294
  add(`${label} must be an object`);
295
295
  continue;
296
296
  }
297
- fields2(resource, ["id", "kind", "purpose", "required", "source"], label);
297
+ fields3(resource, ["id", "kind", "purpose", "required", "source"], label);
298
298
  if (typeof resource.id !== "string" || !identifier2.test(resource.id) || ["constructor", "prototype"].includes(resource.id)) add(`${label} requires a valid identifier`);
299
299
  else if (ids2.has(resource.id)) add(`Duplicate resource id: ${resource.id}`);
300
300
  else ids2.add(resource.id);
@@ -307,7 +307,7 @@ function validateStyleResources(value, expectedId) {
307
307
  continue;
308
308
  }
309
309
  if (source2.type === "local") {
310
- fields2(source2, ["type", "path", "sha256"], `${label} local source`);
310
+ fields3(source2, ["type", "path", "sha256"], `${label} local source`);
311
311
  try {
312
312
  safeStyleResourcePath(source2.path);
313
313
  } catch (error62) {
@@ -315,7 +315,7 @@ function validateStyleResources(value, expectedId) {
315
315
  }
316
316
  if (source2.sha256 !== void 0 && (typeof source2.sha256 !== "string" || !digest.test(source2.sha256))) add(`${label} sha256 must be a 64-character lowercase hexadecimal digest`);
317
317
  } else if (source2.type === "asset") {
318
- fields2(source2, ["type", "assetId", "fileName", "originalPath"], `${label} asset source`);
318
+ fields3(source2, ["type", "assetId", "fileName", "originalPath"], `${label} asset source`);
319
319
  if (typeof source2.assetId !== "string" || !digest.test(source2.assetId)) add(`${label} assetId must be a 64-character lowercase hexadecimal digest`);
320
320
  if (source2.originalPath !== void 0) {
321
321
  try {
@@ -326,7 +326,7 @@ function validateStyleResources(value, expectedId) {
326
326
  }
327
327
  if (source2.fileName !== void 0 && (typeof source2.fileName !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,99}$/.test(source2.fileName))) add(`${label} fileName must be a portable basename, not a path.`);
328
328
  } else if (source2.type === "requirement") {
329
- fields2(source2, ["type", "description"], `${label} requirement source`);
329
+ fields3(source2, ["type", "description"], `${label} requirement source`);
330
330
  text15(source2.description, `${label} requirement description`);
331
331
  } else add(`${label} source must be local, asset or requirement`);
332
332
  }
@@ -478,11 +478,11 @@ function styleReuseIssues(name, value, expectedId) {
478
478
  if (!obj(value) || !(value.schemaVersion === 1 || name === "captions.json" && value.schemaVersion === 2) || value.id !== expectedId) return ["Expected schemaVersion: 1 (or 2 for captions) and id matching the style path."];
479
479
  const errors = [];
480
480
  const add = (s) => errors.push(s);
481
- const fields2 = (v, allowed, label) => {
481
+ const fields3 = (v, allowed, label) => {
482
482
  if (obj(v) && Object.keys(v).some((k) => !allowed.includes(k))) add(`${label} has unsupported fields; store only the documented contract, never credentials.`);
483
483
  };
484
484
  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"] };
485
- fields2(value, ["schemaVersion", "id", ...top[name], ...name === "captions.json" && value.schemaVersion === 2 ? ["renderer", "usage", "referenceSize", "chunk", "pop", "marker"] : []], name);
485
+ fields3(value, ["schemaVersion", "id", ...top[name], ...name === "captions.json" && value.schemaVersion === 2 ? ["renderer", "usage", "referenceSize", "chunk", "pop", "marker"] : []], name);
486
486
  if (name === "techniques.json") {
487
487
  if (!Array.isArray(value.techniques) || value.techniques.length > 100) add("techniques must contain at most 100 entries.");
488
488
  else {
@@ -491,14 +491,14 @@ function styleReuseIssues(name, value, expectedId) {
491
491
  if (!obj(t) || !id(t.id) || seen.has(t.id) || !text3(t.purpose) || !texts2(t.when) || !obj(t.anchor) || t.anchor.kind !== "phrase" || !text3(t.anchor.text) || !ids(t.resourceIds) || !texts2(t.omitWhen) || !texts2(t.verify) || t.componentId !== void 0 && !id(t.componentId)) add('Each technique needs unique id, purpose, when: string[], anchor: {kind:"phrase",text}, resourceIds: string[], omitWhen: string[], verify: string[] and optional componentId.');
492
492
  if (obj(t)) {
493
493
  seen.add(t.id);
494
- fields2(t, ["id", "purpose", "when", "anchor", "resourceIds", "componentId", "omitWhen", "verify"], "Technique");
495
- fields2(t.anchor, ["kind", "text"], "Technique anchor");
494
+ fields3(t, ["id", "purpose", "when", "anchor", "resourceIds", "componentId", "omitWhen", "verify"], "Technique");
495
+ fields3(t.anchor, ["kind", "text"], "Technique anchor");
496
496
  }
497
497
  }
498
498
  }
499
499
  }
500
500
  if (name === "media-style.json") {
501
- fields2(value.animation, ["model", "promptTemplate"], "Animation recipe");
501
+ fields3(value.animation, ["model", "promptTemplate"], "Animation recipe");
502
502
  if (!["draft", "ready"].includes(String(value.status)) || value.model !== void 0 && !text3(value.model) || !ids(value.referenceOrder) || !text3(value.promptTemplate) || !ids(value.variables) || !texts2(value.reviewBeforeAnimation)) add("Media recipe needs status draft|ready, optional model, ordered reference resource IDs, promptTemplate, variables and reviewBeforeAnimation arrays.");
503
503
  if (value.status === "ready" && (!text3(value.model) || !Array.isArray(value.reviewBeforeAnimation) || !value.reviewBeforeAnimation.length)) add("A ready media recipe requires a model and explicit review checks.");
504
504
  if (text3(value.promptTemplate) && Array.isArray(value.variables)) {
@@ -513,10 +513,10 @@ function styleReuseIssues(name, value, expectedId) {
513
513
  const f = value.font, b = value.activeBox, p = value.position, z2 = value.forbiddenZones;
514
514
  if (value.schemaVersion === 2) {
515
515
  const r = value.referenceSize, c = value.chunk, a = value.pop, m = value.marker;
516
- fields2(r, ["width", "height"], "Caption referenceSize");
517
- fields2(c, ["maxWords", "punctuation", "noEndWith"], "Caption chunk");
518
- fields2(a, ["durationSeconds", "scale"], "Caption pop");
519
- fields2(m, ["scope", "roughness", "drawOnSeconds", "seed"], "Caption marker");
516
+ fields3(r, ["width", "height"], "Caption referenceSize");
517
+ fields3(c, ["maxWords", "punctuation", "noEndWith"], "Caption chunk");
518
+ fields3(a, ["durationSeconds", "scale"], "Caption pop");
519
+ fields3(m, ["scope", "roughness", "drawOnSeconds", "seed"], "Caption marker");
520
520
  if (value.renderer !== "builtin-captions-v2" || !["box", "karaoke", "marker"].includes(String(value.mode))) add("Captions v2 needs renderer builtin-captions-v2 and mode box|karaoke|marker; arbitrary modules are not executed.");
521
521
  if (value.usage !== void 0 && value.usage !== "preferred") add("Caption usage is preferred: adapt or omit for the actual video.");
522
522
  if (!obj(r) || !Number.isInteger(r.width) || !Number.isInteger(r.height) || Number(r.width) < 16 || Number(r.height) < 16 || Number(r.width) > 8192 || Number(r.height) > 8192) add("Caption referenceSize needs width/height integers 16..8192; font size and padding are reference pixels.");
@@ -528,10 +528,10 @@ function styleReuseIssues(name, value, expectedId) {
528
528
  if (value.mode !== "marker" && m !== void 0) add("marker settings require marker mode.");
529
529
  }
530
530
  if (value.schemaVersion === 1 && 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.");
531
- fields2(f, ["family", "weight", "size", "color", "resourceId"], "Caption font");
532
- fields2(b, ["color", "padding"], "Caption activeBox");
533
- fields2(p, ["x", "y"], "Caption position");
534
- if (Array.isArray(z2)) for (const zone of z2) fields2(zone, ["x", "y", "width", "height"], "Caption zone");
531
+ fields3(f, ["family", "weight", "size", "color", "resourceId"], "Caption font");
532
+ fields3(b, ["color", "padding"], "Caption activeBox");
533
+ fields3(p, ["x", "y"], "Caption position");
534
+ if (Array.isArray(z2)) for (const zone of z2) fields3(zone, ["x", "y", "width", "height"], "Caption zone");
535
535
  if (obj(f) && f.resourceId !== void 0 && !id(f.resourceId)) add("font.resourceId must name a declared font resource.");
536
536
  if (value.tokenBindings !== void 0 && (!obj(value.tokenBindings) || Object.entries(value.tokenBindings).some(([key, v]) => !["fontFamily", "color", "boxColor"].includes(key) || typeof v !== "string" || !/^[a-z][a-z0-9_.-]{0,79}$/.test(v) || ["constructor", "prototype", "__proto__"].includes(v)))) add("tokenBindings supports fontFamily, color and boxColor mapped to semantic token keys.");
537
537
  if (typeof value.enabled !== "boolean" || !obj(f) || !text3(f.family) || /[\r\n,{}\\]/.test(String(f.family)) || !Number.isInteger(f.weight) || Number(f.weight) < 100 || Number(f.weight) > 900 || typeof f.size !== "number" || !Number.isFinite(f.size) || f.size < 8 || f.size > 300 || !color(f.color) || !obj(b) || !color(b.color) || typeof b.padding !== "number" || !Number.isFinite(b.padding) || b.padding < 0 || b.padding > 100 || !obj(p) || !unit(p.x) || !unit(p.y) || !Array.isArray(z2) || z2.length > 20 || z2.some((a) => !obj(a) || !unit(a.x) || !unit(a.y) || !unit(a.width) || !unit(a.height) || Number(a.x) + Number(a.width) > 1 || Number(a.y) + Number(a.height) > 1) || typeof value.hideDuringCrossings !== "boolean") add("captions needs enabled, font {family,weight:100..900,size:8..300,color:#RRGGBB}, activeBox {color,padding:0..100}, normalized position/zones and hideDuringCrossings boolean.");
@@ -553,11 +553,11 @@ function styleReuseIssues(name, value, expectedId) {
553
553
  }
554
554
  if (c.sourceFormat !== void 0 && !["html", "javascript-module"].includes(String(c.sourceFormat))) add("Component sourceFormat must be html or javascript-module; this declares inert source, not a runnable or deterministic scene.");
555
555
  if (c.sourceFormat === "javascript-module" && typeof c.originPath === "string" && !/\.(m?js)$/i.test(c.originPath)) add("JavaScript module originPath must end in .js or .mjs.");
556
- fields2(c, ["id", "sourceResourceId", "originPath", "sourceFormat", "status", "bindings"], "Component");
556
+ fields3(c, ["id", "sourceResourceId", "originPath", "sourceFormat", "status", "bindings"], "Component");
557
557
  const names = /* @__PURE__ */ new Set();
558
558
  for (const [index, b] of c.bindings.entries()) {
559
559
  const label = `Component ${c.id}, binding ${index + 1}${obj(b) ? " (" + JSON.stringify(b.name) + ")" : ""}`;
560
- fields2(b, ["name", "type", "literal", "occurrences", "role"], label);
560
+ fields3(b, ["name", "type", "literal", "occurrences", "role"], label);
561
561
  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.`);
562
562
  if (obj(b)) names.add(b.name);
563
563
  }
@@ -1045,9 +1045,9 @@ function validateToolPreferences(input2) {
1045
1045
  if (value.schemaVersion !== 1) throw new Error("Tool preferences schemaVersion must be 1.");
1046
1046
  for (const key of ["transcription", "images", "narration", "music"]) {
1047
1047
  if (value[key] === void 0) continue;
1048
- const fields2 = { transcription: ["provider", "language"], images: ["provider", "quality", "resolution", "aspectRatio"], narration: ["provider", "language"], music: ["provider", "durationSeconds", "character"] }[key];
1049
- const section2 = obj3(value[key], fields2);
1050
- if (fields2.some((field) => section2[field] === void 0)) throw new Error("Incomplete AI tool preferences.");
1048
+ const fields3 = { transcription: ["provider", "language"], images: ["provider", "quality", "resolution", "aspectRatio"], narration: ["provider", "language"], music: ["provider", "durationSeconds", "character"] }[key];
1049
+ const section2 = obj3(value[key], fields3);
1050
+ if (fields3.some((field) => section2[field] === void 0)) throw new Error("Incomplete AI tool preferences.");
1051
1051
  const providers = { transcription: transcriptionProviders, images: ["editorbrain", "higgsfield", "openai-images"], narration: ["editorbrain", "elevenlabs"], music: ["editorbrain", "suno", "elevenlabs"] }[key];
1052
1052
  choice(section2.provider, providers);
1053
1053
  if (key === "transcription" || key === "narration") choice(section2.language, toolLanguages);
@@ -1149,10 +1149,10 @@ function validateProjectCheckpoint(input2, projectId) {
1149
1149
  if (!continuity.contextHashes || typeof continuity.contextHashes !== "object" || Array.isArray(continuity.contextHashes)) throw new Error("Checkpoint contextHashes must be an object.");
1150
1150
  const hashes = Object.entries(continuity.contextHashes);
1151
1151
  if (hashes.length > 256) throw new Error("Checkpoint contextHashes must contain at most 256 documents.");
1152
- for (const [path, hash11] of hashes) {
1152
+ for (const [path, hash13] of hashes) {
1153
1153
  const validPath = new RegExp(`^(?:videos/${projectId}/(?:project\\.json|brief\\.md|direction\\.md|script\\.md|media\\.json|audio\\.json|resources\\.json|preferences\\.json|style-decisions\\.json)|\\.editorbrain/(?:brands|styles)/[a-z0-9][a-z0-9_-]{0,79}/[a-z][a-z0-9-]*\\.(?:md|json)|\\.editorbrain/output-profiles/[a-z0-9][a-z0-9_-]{0,79}\\.json)$`);
1154
1154
  const styleSnapshot = path.startsWith(`videos/${projectId}/style-snapshots/`) && styleSnapshotSourcePath(path) !== null;
1155
- if (!validPath.test(path) && !styleSnapshot || typeof hash11 !== "string" || !/^[a-f0-9]{64}$/.test(hash11)) throw new Error("Checkpoint contextHashes requires editorial document paths and lowercase SHA-256 hashes.");
1155
+ if (!validPath.test(path) && !styleSnapshot || typeof hash13 !== "string" || !/^[a-f0-9]{64}$/.test(hash13)) throw new Error("Checkpoint contextHashes requires editorial document paths and lowercase SHA-256 hashes.");
1156
1156
  }
1157
1157
  }
1158
1158
  if (new TextEncoder().encode(JSON.stringify(value)).length > checkpointLimits.documentBytes) throw new Error("Checkpoint must be at most 128 KiB.");
@@ -1926,7 +1926,7 @@ function getMediaStyle(id4, version2) {
1926
1926
  return MEDIA_STYLE_CATALOG.styles.find((style) => style.id === id4 && (version2 === void 0 || style.version === version2));
1927
1927
  }
1928
1928
  var record3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1929
- var only = (value, fields2) => Object.keys(value).every((key) => fields2.includes(key));
1929
+ var only = (value, fields3) => Object.keys(value).every((key) => fields3.includes(key));
1930
1930
  function visualTasteIssues(value) {
1931
1931
  if (!record3(value) || !only(value, ["density", "energy", "contrast"])) return ["visualTaste supports density, energy and contrast only."];
1932
1932
  return Object.entries(visualTasteOptions).flatMap(([key, allowed]) => value[key] === void 0 || typeof value[key] === "string" && allowed.includes(value[key]) ? [] : [`Invalid visualTaste ${key}. Omit undecided choices.`]);
@@ -2055,8 +2055,8 @@ function editorialProfileIssues(value) {
2055
2055
  if (!record4(value)) return ["El perfil editorial debe ser un objeto."];
2056
2056
  const issues = [];
2057
2057
  if (value.schemaVersion !== 1) issues.push("schemaVersion del perfil editorial debe ser 1.");
2058
- const fields2 = [...Object.keys(emptyProfile()), "mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks"];
2059
- if (Object.keys(value).some((key) => !fields2.includes(key))) issues.push("El perfil editorial contiene campos desconocidos.");
2058
+ const fields3 = [...Object.keys(emptyProfile()), "mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks"];
2059
+ if (Object.keys(value).some((key) => !fields3.includes(key))) issues.push("El perfil editorial contiene campos desconocidos.");
2060
2060
  for (const key of ["experience", "role", "goal", "pace", "captions", "sound", "freedom", "assets"]) {
2061
2061
  const selected = value[key];
2062
2062
  if ((key === "experience" || key === "role") && selected === void 0) continue;
@@ -2369,10 +2369,10 @@ function searchSfx(bank, options) {
2369
2369
  const expanded = new Set(terms.flatMap((t) => groups.find((g) => g.includes(t)) ?? [t]));
2370
2370
  const candidates = policy.enabled ? bank.entries.filter((e) => options.includeUnverified || e.license.kind !== "unverified").map((e) => {
2371
2371
  const haystack = new Set(words([e.name, ...e.tags].join(" ")));
2372
- const matches = [...expanded].filter((t) => haystack.has(t));
2373
- return { entry: e, matches, score: matches.length * 4 + (policy.character !== "adaptive" && e.character === policy.character ? 2 : 0) };
2372
+ const matches2 = [...expanded].filter((t) => haystack.has(t));
2373
+ return { entry: e, matches: matches2, score: matches2.length * 4 + (policy.character !== "adaptive" && e.character === policy.character ? 2 : 0) };
2374
2374
  }).filter((e) => !terms.length || e.matches.length > 0).sort((a, b) => b.score - a.score || a.entry.id.localeCompare(b.entry.id)) : [];
2375
- return { bankId: bank.bankId, policy, total: candidates.length, items: candidates.slice(0, options.limit ?? 6).map(({ entry, matches }) => ({ ...entry, matchedTerms: matches })), notice: "Lexical candidates with bilingual tags, not audio understanding. Rights are declared, not independently verified. Audition before use; metadata or a preview is not proof of an audible final mix." };
2375
+ return { bankId: bank.bankId, policy, total: candidates.length, items: candidates.slice(0, options.limit ?? 6).map(({ entry, matches: matches2 }) => ({ ...entry, matchedTerms: matches2 })), notice: "Lexical candidates with bilingual tags, not audio understanding. Rights are declared, not independently verified. Audition before use; metadata or a preview is not proof of an audible final mix." };
2376
2376
  }
2377
2377
  function checkSfxCues(audio, input2) {
2378
2378
  const p = object6(input2, ["durationSeconds", "hookEndSeconds", "cues", "omissionReason"]);
@@ -2474,13 +2474,13 @@ function mergeProfile(base, patch) {
2474
2474
  if (issues.length) throw new Error(issues.join("\n"));
2475
2475
  result2[key] = [.../* @__PURE__ */ new Set([...base.creativePreferencesReviewed ?? [], ...value])];
2476
2476
  } else if (key === "creatorContext") {
2477
- const fields2 = record5(value, key, Object.keys(creatorContextOptions));
2478
- result2[key] = { ...object7(result2[key]) ? result2[key] : {}, ...fields2 };
2477
+ const fields3 = record5(value, key, Object.keys(creatorContextOptions));
2478
+ result2[key] = { ...object7(result2[key]) ? result2[key] : {}, ...fields3 };
2479
2479
  } else if (key === "editorialDelivery" || key === "visualTaste") {
2480
- const fields2 = record5(value, key, key === "editorialDelivery" ? Object.keys(editorialDeliveryOptions) : ["density", "energy", "contrast"]);
2480
+ const fields3 = record5(value, key, key === "editorialDelivery" ? Object.keys(editorialDeliveryOptions) : ["density", "energy", "contrast"]);
2481
2481
  const previous = object7(result2[key]) ? result2[key] : {};
2482
2482
  const next = { ...previous };
2483
- for (const [field, selection] of Object.entries(fields2)) {
2483
+ for (const [field, selection] of Object.entries(fields3)) {
2484
2484
  if (selection === null) delete next[field];
2485
2485
  else if (selection !== void 0) next[field] = selection;
2486
2486
  }
@@ -2547,9 +2547,9 @@ function readOnboardingIdentity(content) {
2547
2547
  const name = [...previous.matchAll(/^# ([^\r\n]+)$/gm)];
2548
2548
  if (name.length === 1 && name[0][1].length <= 100) result2.name = name[0][1];
2549
2549
  for (const [key, heading, max] of [["description", "Qu\xE9 hacemos", 1500], ["audience", "Audiencia", 500], ["tone", "Voz", 500], ["links", "Enlaces compartidos por el usuario", 1500]]) {
2550
- const matches = [...previous.matchAll(new RegExp(`^## ${heading}\\r?\\n([\\s\\S]*?)(?=^#{1,2} |$(?![\\s\\S]))`, "gm"))];
2551
- if (matches.length !== 1) continue;
2552
- let value = matches[0][1].trim();
2550
+ const matches2 = [...previous.matchAll(new RegExp(`^## ${heading}\\r?\\n([\\s\\S]*?)(?=^#{1,2} |$(?![\\s\\S]))`, "gm"))];
2551
+ if (matches2.length !== 1) continue;
2552
+ let value = matches2[0][1].trim();
2553
2553
  if (key === "links") value = value.replace(/\nSon referencias no analizadas\. No asumir su contenido ni consultarlas automáticamente\.$/, "");
2554
2554
  if (value && value !== "Por definir" && value.length <= max) result2[key] = value;
2555
2555
  }
@@ -2867,7 +2867,7 @@ function numeric(value, name, min, max, integer3 = false) {
2867
2867
  if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max || integer3 && !Number.isInteger(value)) throw new Error(`${name} must be ${integer3 ? "an integer" : "a number"} from ${min} to ${max}.`);
2868
2868
  }
2869
2869
  function rasterDimensions(binary, mime2, name) {
2870
- const invalid13 = () => new Error(`${name} has malformed or missing raster dimensions.`);
2870
+ const invalid14 = () => new Error(`${name} has malformed or missing raster dimensions.`);
2871
2871
  const byte = (offset2) => binary.charCodeAt(offset2);
2872
2872
  const u16 = (offset2) => byte(offset2) * 256 + byte(offset2 + 1);
2873
2873
  const u32 = (offset2) => u16(offset2) * 65536 + u16(offset2 + 2);
@@ -2875,50 +2875,50 @@ function rasterDimensions(binary, mime2, name) {
2875
2875
  const le24 = (offset2) => le16(offset2) + byte(offset2 + 2) * 65536;
2876
2876
  const le32 = (offset2) => le24(offset2) + byte(offset2 + 3) * 16777216;
2877
2877
  const check2 = (width, height) => {
2878
- if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw invalid13();
2878
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw invalid14();
2879
2879
  if (width > MOTION_INPUT_LIMITS.maxImageDimension || height > MOTION_INPUT_LIMITS.maxImageDimension || width * height > MOTION_INPUT_LIMITS.maxImagePixels) throw new Error(`${name} raster dimensions exceed ${MOTION_INPUT_LIMITS.maxImageDimension} pixels per side or ${MOTION_INPUT_LIMITS.maxImagePixels} total pixels.`);
2880
2880
  };
2881
2881
  if (mime2 === "image/png") {
2882
- if (u32(8) !== 13) throw invalid13();
2882
+ if (u32(8) !== 13) throw invalid14();
2883
2883
  check2(u32(16), u32(20));
2884
2884
  return;
2885
2885
  }
2886
2886
  if (mime2 === "image/jpeg") {
2887
2887
  let offset2 = 2, dimensions;
2888
2888
  while (offset2 < binary.length) {
2889
- if (byte(offset2++) !== 255) throw invalid13();
2889
+ if (byte(offset2++) !== 255) throw invalid14();
2890
2890
  while (offset2 < binary.length && byte(offset2) === 255) offset2++;
2891
- if (offset2 >= binary.length) throw invalid13();
2891
+ if (offset2 >= binary.length) throw invalid14();
2892
2892
  const marker = byte(offset2++);
2893
2893
  if (marker === 217 || marker === 218) break;
2894
- if (marker === 216 || marker === 0) throw invalid13();
2894
+ if (marker === 216 || marker === 0) throw invalid14();
2895
2895
  if (marker === 1 || marker >= 208 && marker <= 215) continue;
2896
- if (offset2 + 2 > binary.length) throw invalid13();
2896
+ if (offset2 + 2 > binary.length) throw invalid14();
2897
2897
  const size = u16(offset2);
2898
- if (size < 2 || offset2 + size > binary.length) throw invalid13();
2898
+ if (size < 2 || offset2 + size > binary.length) throw invalid14();
2899
2899
  if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker)) {
2900
- if (size < 11 || size !== 8 + byte(offset2 + 7) * 3) throw invalid13();
2900
+ if (size < 11 || size !== 8 + byte(offset2 + 7) * 3) throw invalid14();
2901
2901
  const width = u16(offset2 + 5), height = u16(offset2 + 3);
2902
2902
  check2(width, height);
2903
- if (dimensions && (dimensions[0] !== width || dimensions[1] !== height)) throw invalid13();
2903
+ if (dimensions && (dimensions[0] !== width || dimensions[1] !== height)) throw invalid14();
2904
2904
  dimensions = [width, height];
2905
2905
  }
2906
2906
  offset2 += size;
2907
2907
  }
2908
- if (!dimensions) throw invalid13();
2908
+ if (!dimensions) throw invalid14();
2909
2909
  return;
2910
2910
  }
2911
- if (le32(4) !== binary.length - 8) throw invalid13();
2911
+ if (le32(4) !== binary.length - 8) throw invalid14();
2912
2912
  const frameDimensions = (kind2, size, data) => {
2913
2913
  if (kind2 === "VP8L") {
2914
- if (size < 5 || byte(data) !== 47 || byte(data + 4) >> 5 !== 0) throw invalid13();
2914
+ if (size < 5 || byte(data) !== 47 || byte(data + 4) >> 5 !== 0) throw invalid14();
2915
2915
  const width = 1 + (byte(data + 1) | (byte(data + 2) & 63) << 8);
2916
2916
  const height = 1 + (byte(data + 2) >> 6 | byte(data + 3) << 2 | (byte(data + 4) & 15) << 10);
2917
2917
  check2(width, height);
2918
2918
  return true;
2919
2919
  }
2920
2920
  if (kind2 === "VP8 ") {
2921
- if (size < 10 || byte(data) & 1 || binary.slice(data + 3, data + 6) !== "\x9D*") throw invalid13();
2921
+ if (size < 10 || byte(data) & 1 || binary.slice(data + 3, data + 6) !== "\x9D*") throw invalid14();
2922
2922
  check2(le16(data + 6) & 16383, le16(data + 8) & 16383);
2923
2923
  return true;
2924
2924
  }
@@ -2927,26 +2927,26 @@ function rasterDimensions(binary, mime2, name) {
2927
2927
  let offset = 12, found = false;
2928
2928
  while (offset + 8 <= binary.length) {
2929
2929
  const kind2 = binary.slice(offset, offset + 4), size = le32(offset + 4), data = offset + 8;
2930
- if (size > binary.length - data) throw invalid13();
2930
+ if (size > binary.length - data) throw invalid14();
2931
2931
  if (kind2 === "VP8X") {
2932
- if (size !== 10) throw invalid13();
2932
+ if (size !== 10) throw invalid14();
2933
2933
  check2(le24(data + 4) + 1, le24(data + 7) + 1);
2934
2934
  found = true;
2935
2935
  } else if (kind2 === "ANMF") {
2936
- if (size < 16) throw invalid13();
2936
+ if (size < 16) throw invalid14();
2937
2937
  check2(le24(data + 6) + 1, le24(data + 9) + 1);
2938
2938
  let nested = data + 16, frame = false;
2939
2939
  while (nested + 8 <= data + size) {
2940
2940
  const frameKind = binary.slice(nested, nested + 4), frameSize = le32(nested + 4), frameData = nested + 8;
2941
- if (frameSize > data + size - frameData) throw invalid13();
2941
+ if (frameSize > data + size - frameData) throw invalid14();
2942
2942
  frame = frameDimensions(frameKind, frameSize, frameData) || frame;
2943
2943
  nested = frameData + frameSize + frameSize % 2;
2944
2944
  }
2945
- if (!frame || nested !== data + size) throw invalid13();
2945
+ if (!frame || nested !== data + size) throw invalid14();
2946
2946
  } else found = frameDimensions(kind2, size, data) || found;
2947
2947
  offset = data + size + size % 2;
2948
2948
  }
2949
- if (!found || offset !== binary.length) throw invalid13();
2949
+ if (!found || offset !== binary.length) throw invalid14();
2950
2950
  }
2951
2951
  function dataUrl(value, name, kind2) {
2952
2952
  const max = kind2 === "font" ? MOTION_INPUT_LIMITS.fontBytes : MOTION_INPUT_LIMITS.imageBytes;
@@ -7001,16 +7001,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
7001
7001
  };
7002
7002
  });
7003
7003
  function handleExclusiveUnionResults(results, final, inst, ctx) {
7004
- const matches = [];
7004
+ const matches2 = [];
7005
7005
  for (let i = 0; i < results.length; i++) {
7006
7006
  if (results[i].issues.length === 0)
7007
- matches.push(i);
7007
+ matches2.push(i);
7008
7008
  }
7009
- if (matches.length === 1) {
7010
- final.value = results[matches[0]].value;
7009
+ if (matches2.length === 1) {
7010
+ final.value = results[matches2[0]].value;
7011
7011
  return final;
7012
7012
  }
7013
- if (matches.length === 0) {
7013
+ if (matches2.length === 0) {
7014
7014
  final.issues.push({
7015
7015
  code: "invalid_union",
7016
7016
  input: final.value,
@@ -7024,7 +7024,7 @@ function handleExclusiveUnionResults(results, final, inst, ctx) {
7024
7024
  inst,
7025
7025
  errors: [],
7026
7026
  inclusive: false,
7027
- matches
7027
+ matches: matches2
7028
7028
  });
7029
7029
  }
7030
7030
  return final;
@@ -22223,20 +22223,20 @@ function checkArrayGuards(arraySchema, guards) {
22223
22223
  if (guards.containsSchema) {
22224
22224
  const minContains = guards.minContains ?? 1;
22225
22225
  const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
22226
- let matches = 0;
22226
+ let matches2 = 0;
22227
22227
  for (const item of items) {
22228
- if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
22228
+ if (guards.containsSchema.safeParse(item).success && ++matches2 >= ceiling)
22229
22229
  break;
22230
22230
  }
22231
- if (matches < minContains) {
22231
+ if (matches2 < minContains) {
22232
22232
  payload.issues.push({
22233
22233
  code: "custom",
22234
- message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
22234
+ message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches2}`,
22235
22235
  input: items,
22236
22236
  continue: true
22237
22237
  });
22238
22238
  }
22239
- if (guards.maxContains !== void 0 && matches > guards.maxContains) {
22239
+ if (guards.maxContains !== void 0 && matches2 > guards.maxContains) {
22240
22240
  payload.issues.push({
22241
22241
  code: "custom",
22242
22242
  message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
@@ -201728,7 +201728,7 @@ var searchIndexes = { "1.1.0": buildSearchIndex(catalogs["1.1.0"]), "1.2.0": bui
201728
201728
  var bilingualIndex = buildSearchIndex(catalogs["1.4.0"], true);
201729
201729
  function termWeights(index) {
201730
201730
  const frequencies = /* @__PURE__ */ new Map();
201731
- for (const { fields: fields2 } of index) for (const term of new Set(fields2.flatMap((field) => [...field.terms]))) {
201731
+ for (const { fields: fields3 } of index) for (const term of new Set(fields3.flatMap((field) => [...field.terms]))) {
201732
201732
  frequencies.set(term, (frequencies.get(term) ?? 0) + 1);
201733
201733
  }
201734
201734
  return new Map([...frequencies].map(([term, count2]) => [term, 1 + Math.log((index.length + 1) / (count2 + 1))]));
@@ -201742,23 +201742,23 @@ function rankedCandidates(search, version2, bilingual = false) {
201742
201742
  if (exact) return [exact];
201743
201743
  const queryTerms = bilingual ? discoveryTerms(search) : stems(search);
201744
201744
  if (version2 === "1.4.0") queryTerms.delete("quien");
201745
- return searchIndex.map(({ scene, fields: fields2 }) => {
201745
+ return searchIndex.map(({ scene, fields: fields3 }) => {
201746
201746
  if (version2 === "1.4.0") {
201747
201747
  let score = 0, coverage = 0;
201748
201748
  for (const term of queryTerms) {
201749
- const fieldWeight = fields2.reduce((sum, field) => sum + (field.terms.has(term) ? field.weight : 0), 0);
201749
+ const fieldWeight = fields3.reduce((sum, field) => sum + (field.terms.has(term) ? field.weight : 0), 0);
201750
201750
  if (!fieldWeight) continue;
201751
201751
  const rarity = (bilingual ? bilingualTermWeights : v14TermWeights).get(term);
201752
- const mechanismBoost = bilingual && mechanismTerms.has(term) && fields2.slice(0, 2).some((field) => field.terms.has(term)) ? 3 : 1;
201752
+ const mechanismBoost = bilingual && mechanismTerms.has(term) && fields3.slice(0, 2).some((field) => field.terms.has(term)) ? 3 : 1;
201753
201753
  score += rarity * Math.sqrt(fieldWeight) * mechanismBoost;
201754
201754
  coverage += rarity;
201755
201755
  }
201756
201756
  return { scene, score: score * Math.sqrt(coverage) };
201757
201757
  }
201758
- return { scene, score: fields2.reduce((total, field) => {
201759
- let matches = 0;
201760
- for (const term of queryTerms) if (field.terms.has(term)) matches++;
201761
- return total + matches * field.weight;
201758
+ return { scene, score: fields3.reduce((total, field) => {
201759
+ let matches2 = 0;
201760
+ for (const term of queryTerms) if (field.terms.has(term)) matches2++;
201761
+ return total + matches2 * field.weight;
201762
201762
  }, 0) };
201763
201763
  }).filter((result2) => result2.score > 0).sort((a, b) => b.score - a.score || (a.scene.id < b.scene.id ? -1 : a.scene.id > b.scene.id ? 1 : 0)).map((result2) => result2.scene);
201764
201764
  }
@@ -201879,12 +201879,12 @@ var SOCIAL_SAFE_PROFILES = {
201879
201879
  reels: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 },
201880
201880
  shorts: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 }
201881
201881
  };
201882
- function validateVisualReview(value, hash11, duration3, width, height) {
201882
+ function validateVisualReview(value, hash13, duration3, width, height) {
201883
201883
  const v = value;
201884
201884
  const fail4 = () => {
201885
201885
  throw new Error("Invalid visual profile: use the exact artifact hash, output-clock seconds and output-pixel boxes.");
201886
201886
  };
201887
- if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash11 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail4();
201887
+ if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash13 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail4();
201888
201888
  if (Object.keys(v).some((k) => !["schemaVersion", "artifactSha256", "platform", "holds", "geometry"].includes(k))) fail4();
201889
201889
  if (v.platform !== void 0 && !Object.hasOwn(SOCIAL_SAFE_PROFILES, v.platform)) fail4();
201890
201890
  if (v.holds !== void 0 && (!Array.isArray(v.holds) || v.holds.length > 1e3)) fail4();
@@ -202574,6 +202574,96 @@ function findPublicTaskRoute(query) {
202574
202574
  return PUBLIC_TASK_ROUTES.find((route) => route.id === key || route.aliases.some((alias) => taskKey(alias) === key));
202575
202575
  }
202576
202576
 
202577
+ // packages/core/src/review-readiness.ts
202578
+ var reviewArtifactPhases = ["directions", "review", "delivery"];
202579
+ var identifier8 = /^[a-zA-Z0-9_-]{1,80}$/;
202580
+ var uuid5 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
202581
+ var hash5 = /^[a-f0-9]{64}$/;
202582
+ function fields2(value, required2, optional2, label) {
202583
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
202584
+ const result2 = value;
202585
+ if (required2.some((key) => !Object.hasOwn(result2, key)) || Object.keys(result2).some((key) => !required2.includes(key) && !optional2.includes(key))) {
202586
+ throw new Error(`${label} has missing or unsupported fields.`);
202587
+ }
202588
+ return result2;
202589
+ }
202590
+ function matches(value, pattern, label) {
202591
+ if (typeof value !== "string" || !pattern.test(value)) throw new Error(`Invalid review evidence ${label}.`);
202592
+ }
202593
+ function parseReviewEvidence(input2) {
202594
+ const value = fields2(input2, ["evidenceId", "projectId", "contextVersion", "phase", "source", "presented"], ["decision"], "Review evidence");
202595
+ matches(value.evidenceId, uuid5, "evidenceId: use a lowercase UUID");
202596
+ matches(value.projectId, identifier8, "projectId");
202597
+ matches(value.contextVersion, hash5, "contextVersion: use the shared editorial SHA-256");
202598
+ if (!reviewArtifactPhases.includes(value.phase)) throw new Error("Review evidence phase must be directions, review or delivery.");
202599
+ if (value.presented !== true) throw new Error("Review evidence requires an explicit presented: true attestation; creating or opening a file is not presentation.");
202600
+ const phase = value.phase;
202601
+ let source2;
202602
+ if (value.source && typeof value.source === "object" && "kind" in value.source && value.source.kind === "revision") {
202603
+ const item = fields2(value.source, ["kind", "revisionId"], [], "Review evidence revision source");
202604
+ matches(item.revisionId, uuid5, "source.revisionId");
202605
+ source2 = { kind: "revision", revisionId: item.revisionId };
202606
+ } else {
202607
+ const item = fields2(value.source, ["kind", "artifactId", "sha256", "relativePath"], [], "Review evidence local source");
202608
+ if (item.kind !== "local") throw new Error("Review evidence source.kind must be revision or local.");
202609
+ matches(item.artifactId, hash5, "source.artifactId");
202610
+ matches(item.sha256, hash5, "source.sha256");
202611
+ if (typeof item.relativePath !== "string") throw new Error("Review evidence source.relativePath must be a portable relative path.");
202612
+ try {
202613
+ assertCheckpointArtifactPath(item.relativePath);
202614
+ } catch {
202615
+ throw new Error("Review evidence source.relativePath must be a safe portable relative file path, without absolute paths, URLs, credentials or traversal.");
202616
+ }
202617
+ source2 = { kind: "local", artifactId: item.artifactId, sha256: item.sha256, relativePath: item.relativePath };
202618
+ }
202619
+ let decision;
202620
+ if (Object.hasOwn(value, "decision")) {
202621
+ if (source2.kind !== "local") throw new Error("Remote review approval must come from the existing revision; do not duplicate it in review evidence.");
202622
+ if (phase === "delivery") throw new Error("Delivery evidence does not record final acceptance; use the existing final acceptance flow.");
202623
+ const item = fields2(value.decision, phase === "directions" ? ["userConfirmed", "directionId"] : ["userConfirmed", "approved"], [], "Local review decision");
202624
+ if (item.userConfirmed !== true) throw new Error("A local review decision requires explicit userConfirmed: true.");
202625
+ if (phase === "directions") {
202626
+ matches(item.directionId, identifier8, "decision.directionId");
202627
+ decision = { userConfirmed: true, directionId: item.directionId };
202628
+ } else {
202629
+ if (item.approved !== true) throw new Error("A local sample decision requires approved: true for this exact artifact.");
202630
+ decision = { userConfirmed: true, approved: true };
202631
+ }
202632
+ }
202633
+ return { evidenceId: value.evidenceId, projectId: value.projectId, contextVersion: value.contextVersion, phase, source: source2, presented: true, ...decision ? { decision } : {} };
202634
+ }
202635
+ function parseProjectReviewReadiness(input2) {
202636
+ const value = fields2(input2, ["schemaVersion", "kind", "projectId", "contextVersion", "reviewMode", "production", "delivery"], [], "Project review readiness");
202637
+ if (value.schemaVersion !== 1 || value.kind !== "editorbrain.review-readiness") throw new Error("Unsupported project review readiness format.");
202638
+ matches(value.projectId, identifier8, "projectId");
202639
+ if (value.contextVersion !== null) matches(value.contextVersion, hash5, "contextVersion");
202640
+ if (value.reviewMode !== null && !["direct", "directions", "sample"].includes(value.reviewMode)) throw new Error("Invalid review readiness mode.");
202641
+ const parseGate = (input3) => {
202642
+ const item = fields2(input3, ["status", "phase", "reason", "evidence", "next"], [], "Review readiness gate");
202643
+ if (!["satisfied", "pending", "stale", "unknown", "not_required"].includes(item.status)) throw new Error("Invalid review readiness status.");
202644
+ if (item.phase !== null && !reviewArtifactPhases.includes(item.phase)) throw new Error("Invalid review readiness phase.");
202645
+ matches(item.reason, /^[a-z][a-z_]{0,119}$/, "readiness reason");
202646
+ if (item.next !== null && (typeof item.next !== "string" || !item.next.trim() || item.next.length > 2e3 || /[\p{Cc}\p{Cf}]/u.test(item.next))) throw new Error("Invalid review readiness next action.");
202647
+ let evidence = null;
202648
+ if (item.evidence !== null) {
202649
+ const ref = fields2(item.evidence, ["evidenceId", "phase", "source"], [], "Review readiness evidence reference");
202650
+ const parsed = parseReviewEvidence({ ...ref, projectId: value.projectId, contextVersion: value.contextVersion ?? "0".repeat(64), presented: true });
202651
+ if (parsed.phase !== item.phase) throw new Error("Review readiness evidence phase must match its gate.");
202652
+ evidence = { evidenceId: parsed.evidenceId, phase: parsed.phase, source: parsed.source };
202653
+ }
202654
+ return { status: item.status, phase: item.phase, reason: item.reason, evidence, next: item.next };
202655
+ };
202656
+ return {
202657
+ schemaVersion: 1,
202658
+ kind: "editorbrain.review-readiness",
202659
+ projectId: value.projectId,
202660
+ contextVersion: value.contextVersion,
202661
+ reviewMode: value.reviewMode,
202662
+ production: parseGate(value.production),
202663
+ delivery: parseGate(value.delivery)
202664
+ };
202665
+ }
202666
+
202577
202667
  // packages/core/src/index.ts
202578
202668
  var SCHEMA_VERSION = 1;
202579
202669
  var MAX_DOCUMENT_BYTES = 128 * 1024;
@@ -202586,7 +202676,7 @@ var ValidationError = class extends Error {
202586
202676
  }
202587
202677
  issues;
202588
202678
  };
202589
- var identifier8 = /^[a-z0-9][a-z0-9_-]{0,79}$/;
202679
+ var identifier9 = /^[a-z0-9][a-z0-9_-]{0,79}$/;
202590
202680
  var tokenName = /^[a-z][a-z0-9_.-]{0,79}$/;
202591
202681
  var tokenNameHelp = "Use 1\u201380 characters: start with a lowercase letter, then lowercase letters, digits, _, . or - (for example font_family). __proto__, constructor and prototype are reserved. Keys are flat semantic names, not CSS property names.";
202592
202682
  var own5 = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
@@ -202595,7 +202685,7 @@ var nonempty2 = (value) => typeof value === "string" && value.trim().length > 0;
202595
202685
  var finite = (value) => typeof value === "number" && Number.isFinite(value);
202596
202686
  var tokenValue = (value) => typeof value === "string" || typeof value === "boolean" || finite(value) || Array.isArray(value) && value.every((v) => typeof v === "string");
202597
202687
  function assertIdentifier(value) {
202598
- if (!identifier8.test(value)) throw new Error(`Invalid identifier: ${value}. Use lowercase letters, numbers, _ or - (max 80).`);
202688
+ if (!identifier9.test(value)) throw new Error(`Invalid identifier: ${value}. Use lowercase letters, numbers, _ or - (max 80).`);
202599
202689
  return value;
202600
202690
  }
202601
202691
  function safeDocumentPath(path) {
@@ -202703,7 +202793,7 @@ function validateDocument(path, content) {
202703
202793
  }
202704
202794
  if (isBrand || isStyle || isProject || isOutput) {
202705
202795
  const expected = isOutput ? parts[2].slice(0, -5) : parts[isProject ? 1 : 2];
202706
- if (!identifier8.test(expected)) add("Invalid resource identifier in path");
202796
+ if (!identifier9.test(expected)) add("Invalid resource identifier in path");
202707
202797
  if (doc.id !== void 0 && doc.id !== expected) add(`Document id must match path: ${expected}`);
202708
202798
  }
202709
202799
  if (parts[0] === ".editorbrain" && parts[1] === "sfx") {
@@ -202761,7 +202851,7 @@ function validateDocument(path, content) {
202761
202851
  }
202762
202852
  }
202763
202853
  if (isProject) {
202764
- for (const key of ["id", "brand", "style", "outputProfile"]) if (typeof doc[key] !== "string" || !identifier8.test(doc[key])) add(`${key} must be a valid identifier`);
202854
+ for (const key of ["id", "brand", "style", "outputProfile"]) if (typeof doc[key] !== "string" || !identifier9.test(doc[key])) add(`${key} must be a valid identifier`);
202765
202855
  if (!object10(doc.intent) || !nonempty2(doc.intent.topic) || !nonempty2(doc.intent.goal)) add("intent requires topic and goal");
202766
202856
  for (const issue3 of creativeDirectionIssues(doc.creativeDirection)) add(issue3);
202767
202857
  for (const issue3 of questionModeIssues(doc.questionMode)) add(issue3);
@@ -202780,7 +202870,7 @@ function validateDocument(path, content) {
202780
202870
  }
202781
202871
  }
202782
202872
  if (isMedia) {
202783
- if (!identifier8.test(parts[1])) add("Invalid project identifier in media path");
202873
+ if (!identifier9.test(parts[1])) add("Invalid project identifier in media path");
202784
202874
  if (!Array.isArray(doc.assets)) add("Production media requires an assets array");
202785
202875
  else {
202786
202876
  const ids2 = /* @__PURE__ */ new Set();
@@ -203318,7 +203408,7 @@ async function copyReviewFile(source2, target, maxBytes = LOCAL_REVIEW_MEDIA_BYT
203318
203408
  const before = await input2.stat();
203319
203409
  if (!before.isFile() || before.size <= 0 || before.size > maxBytes) throw new CliError("INVALID_REVIEW_FILE", "Review media is empty, not regular or exceeds its size limit.", `Use a separate review copy under ${maxBytes / 1024 / 1024} MiB. Keep the original.`);
203320
203410
  output3 = await open3(target, "wx", 384);
203321
- const buffer = Buffer.alloc(4 * 1024 * 1024), hash11 = createHash("sha256");
203411
+ const buffer = Buffer.alloc(4 * 1024 * 1024), hash13 = createHash("sha256");
203322
203412
  let length = 0;
203323
203413
  for (; ; ) {
203324
203414
  const { bytesRead } = await input2.read(buffer, 0, buffer.length, length);
@@ -203326,7 +203416,7 @@ async function copyReviewFile(source2, target, maxBytes = LOCAL_REVIEW_MEDIA_BYT
203326
203416
  length += bytesRead;
203327
203417
  if (length > before.size) throw new CliError("REVIEW_FILE_CHANGED", "Review media changed while copying.", "Finish rendering and create a new review.");
203328
203418
  const chunk = buffer.subarray(0, bytesRead);
203329
- hash11.update(chunk);
203419
+ hash13.update(chunk);
203330
203420
  let written = 0;
203331
203421
  while (written < chunk.length) {
203332
203422
  const result2 = await output3.write(chunk, written, chunk.length - written);
@@ -203338,7 +203428,7 @@ async function copyReviewFile(source2, target, maxBytes = LOCAL_REVIEW_MEDIA_BYT
203338
203428
  if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new CliError("REVIEW_FILE_CHANGED", "Review media changed while copying.", "Finish rendering and create a new review.");
203339
203429
  await verifyReviewPath(source2, before);
203340
203430
  complete = true;
203341
- return { bytes: length, sha256: hash11.digest("hex") };
203431
+ return { bytes: length, sha256: hash13.digest("hex") };
203342
203432
  } finally {
203343
203433
  await input2.close();
203344
203434
  await output3?.close();
@@ -203550,17 +203640,17 @@ async function videoEvidenceHash(path, expectedSize) {
203550
203640
  try {
203551
203641
  const before = await handle.stat();
203552
203642
  if (!before.isFile() || before.size !== expectedSize) throw new Error("Video changed before hashing");
203553
- const hash11 = createHash2("sha256"), chunk = Buffer.alloc(1024 * 1024);
203643
+ const hash13 = createHash2("sha256"), chunk = Buffer.alloc(1024 * 1024);
203554
203644
  let offset = 0;
203555
203645
  while (offset < before.size) {
203556
203646
  const { bytesRead } = await handle.read(chunk, 0, Math.min(chunk.length, before.size - offset), offset);
203557
203647
  if (!bytesRead) throw new Error("Video changed while hashing");
203558
- hash11.update(chunk.subarray(0, bytesRead));
203648
+ hash13.update(chunk.subarray(0, bytesRead));
203559
203649
  offset += bytesRead;
203560
203650
  }
203561
203651
  const after = await handle.stat();
203562
203652
  if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new Error("Video changed while hashing");
203563
- return hash11.digest("hex");
203653
+ return hash13.digest("hex");
203564
203654
  } finally {
203565
203655
  await handle.close();
203566
203656
  }
@@ -203718,9 +203808,9 @@ async function buildStyleFromProject(root, id4, projectId, name, scenePath) {
203718
203808
  warnings.push(`Final render evidence budget (2 GiB): omitted ${path} (${size} bytes).`);
203719
203809
  continue;
203720
203810
  }
203721
- const hash12 = await videoEvidenceHash(await checkedPath(root, path, false), size);
203811
+ const hash14 = await videoEvidenceHash(await checkedPath(root, path, false), size);
203722
203812
  evidenceBytes += size;
203723
- examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, sha256: hash12, evidence: "final_render_local_hash_only", reviewStatus: "unreviewed" });
203813
+ examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, sha256: hash14, evidence: "final_render_local_hash_only", reviewStatus: "unreviewed" });
203724
203814
  warnings.push(`Final render recorded by hash only; not uploaded: ${path} (${size} bytes).`);
203725
203815
  continue;
203726
203816
  }
@@ -203736,7 +203826,7 @@ async function buildStyleFromProject(root, id4, projectId, name, scenePath) {
203736
203826
  const bytes = await readReviewFile(await checkedPath(root, path, false), 90 * 1024 * 1024);
203737
203827
  bytesRead += bytes.length;
203738
203828
  assertPortableStyleCode(bytes, path);
203739
- const hash11 = digest3(bytes), existing = hashes.get(hash11);
203829
+ const hash13 = digest3(bytes), existing = hashes.get(hash13);
203740
203830
  if (existing) {
203741
203831
  duplicatePaths.push({ path, resourceId: existing });
203742
203832
  continue;
@@ -203746,8 +203836,8 @@ async function buildStyleFromProject(root, id4, projectId, name, scenePath) {
203746
203836
  continue;
203747
203837
  }
203748
203838
  const rid = `resource-${resources.length + 1}`;
203749
- hashes.set(hash11, rid);
203750
- 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: hash11 } });
203839
+ hashes.set(hash13, rid);
203840
+ 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: hash13 } });
203751
203841
  } catch (error62) {
203752
203842
  warnings.push(`Resource unavailable or unsupported: ${path}: ${error62.message}`);
203753
203843
  if (resources.length < 200) resources.push({ id: `resource-${resources.length + 1}`, kind: kind(path), purpose: `Untransported source ${posix2.basename(path)}; inspect locally.`, required: true, source: { type: "requirement", description: "The source was not copied because it failed the portable-file checks. Redact private content or replace it with a safe declared dependency before reuse." } });
@@ -204046,14 +204136,14 @@ async function checkLocalResource(root, path, expected) {
204046
204136
  const before = await handle.stat();
204047
204137
  if (!before.isFile()) throw new Error("Resource is not a regular file.");
204048
204138
  if (!expected) return {};
204049
- const hash11 = createHash3("sha256");
204050
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash11.update(chunk);
204139
+ const hash13 = createHash3("sha256");
204140
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash13.update(chunk);
204051
204141
  const after = await handle.stat();
204052
204142
  const current2 = await lstat5(await checkedPath(root, path, false));
204053
204143
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
204054
204144
  throw new Error("Resource changed while its hash was being checked; check it again.");
204055
204145
  }
204056
- return { actualSha256: hash11.digest("hex") };
204146
+ return { actualSha256: hash13.digest("hex") };
204057
204147
  } finally {
204058
204148
  await handle.close();
204059
204149
  }
@@ -204142,6 +204232,13 @@ import { posix as posix3 } from "node:path";
204142
204232
  // packages/cli/src/client.ts
204143
204233
  import { setTimeout as delay } from "node:timers/promises";
204144
204234
  var searchErrors = {
204235
+ review_required: { status: 409, code: "REVIEW_REQUIRED", hint: "Read workflow check --project ID and production present --project ID. Deliver the missing visual artifact, then record the real selection or approval for that exact context. Technical previews remain available. Preserve existing approvals and explicit direct mode; never change the mode to bypass review." },
204236
+ invalid_review_evidence: { status: 400, code: "INVALID_REVIEW_EVIDENCE", hint: "Read production present --help and the current evidence/version. Use explicit presented:true, an exact contextVersion and a source revision or verified local artifact. A generated/uploaded file is not proof of presentation; never invent user approval." },
204237
+ review_evidence_changed: { status: 409, code: "REVIEW_EVIDENCE_CHANGED", hint: "Read production present --project ID again. Reconcile changed project context, presentation receipts, feedback or approvals and use its current version. Do not silently reapprove or repeat a paid render." },
204238
+ review_evidence_conflict: { status: 409, code: "REVIEW_EVIDENCE_CONFLICT", hint: "This evidenceId already identifies different immutable evidence. Read production present --project ID and reconcile it. Retry the same bytes with the same ID; use a new ID only for an actually new presentation, never to bypass a conflict." },
204239
+ review_evidence_limit: { status: 409, code: "REVIEW_EVIDENCE_LIMIT", hint: "Read production present --project ID and reuse the receipt for the same artifact. Preserve history; do not create duplicate presentations or delete evidence to bypass the limit." },
204240
+ review_unavailable: { status: 409, code: "REVIEW_UNAVAILABLE", hint: "Read production reviews --project ID. Select the available, current, non-superseded revision that was actually presented; preserve comments and do not silently substitute or approve another version." },
204241
+ invalid_continuity_cursor: { status: 400, code: "INVALID_CONTINUITY_CURSOR", hint: "Read project continuity with the exact cursors returned for this project. An older API may not support optional review evidence; never change project or workspace to bypass this error." },
204145
204242
  brand_limit_reached: { status: 409, code: "BRAND_LIMIT_REACHED", hint: "Consulta el l\xEDmite de marcas de este espacio en https://editorbrain.com/app/billing. Puedes seguir editando las existentes. Comprar cr\xE9ditos no aumenta este l\xEDmite." },
204146
204243
  invalid_project_intake: { status: 400, code: "INVALID_PROJECT_INTAKE", hint: "Use projects create ID --brand ID --style ID --output-profile ID with existing IDs. The workspace comes from your authenticated account; do not send a workspace ID." },
204147
204244
  project_dependency_missing: { status: 404, code: "PROJECT_DEPENDENCY_MISSING", hint: "Read dependencyKind and documentPath. Discover the existing brand with brands list and styles/output profiles with documents list --prefix .editorbrain/styles/ or .editorbrain/output-profiles/. Preserve saved choices; do not invent replacement preferences or select another brand silently." },
@@ -204218,7 +204315,7 @@ var searchErrors = {
204218
204315
  studio_insufficient_credits: { status: 402, code: "STUDIO_INSUFFICIENT_CREDITS", hint: "Check studio catalog for available creative credits. Reconnecting does not replenish credits." },
204219
204316
  studio_quote_expired: { status: 409, code: "STUDIO_QUOTE_EXPIRED", hint: "Request a new quote and review its price before authorizing." },
204220
204317
  studio_budget_exceeded: { status: 409, code: "STUDIO_BUDGET_EXCEEDED", hint: "The quote exceeds the authorized budget. Do not increase it yourself." },
204221
- stale_context: { status: 409, code: "STALE_CONTEXT", hint: "Read the current project preferences and request a new quote." },
204318
+ stale_context: { status: 409, code: "STALE_CONTEXT", hint: "Read the current project preferences and workflow. For presentation, reconcile the exact artifact and production present state; never copy an approval onto changed work. For generation/rendering, request a new quote." },
204222
204319
  studio_preference_conflict: { status: 409, code: "STUDIO_PREFERENCE_CONFLICT", hint: "Reconcile project language, voice, music or media-source preferences before generating." },
204223
204320
  studio_audio_format: { status: 422, code: "STUDIO_AUDIO_FORMAT", hint: "Prepare PCM 16-bit WAV from the original with studio prepare, then upload it." },
204224
204321
  studio_invalid_input: { status: 400, code: "STUDIO_INVALID_INPUT", hint: "Check studio catalog and the request fields; never send provider credentials." },
@@ -204256,6 +204353,10 @@ function safeDiagnosticDetails(body) {
204256
204353
  const e = body?.error;
204257
204354
  if (!e || typeof e !== "object") return {};
204258
204355
  const details = {};
204356
+ if (e.code === "review_required") {
204357
+ if (typeof e.projectId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(e.projectId)) details.projectId = e.projectId;
204358
+ if (["directions", "review", "delivery"].includes(String(e.phase))) details.phase = String(e.phase);
204359
+ }
204259
204360
  if (e.code === "project_dependency_missing") {
204260
204361
  if (["brand", "style", "outputProfile"].includes(String(e.dependencyKind))) details.dependencyKind = String(e.dependencyKind);
204261
204362
  if (typeof e.documentPath === "string" && /^\.editorbrain\/(?:(?:brands|styles)\/[a-z0-9][a-z0-9_-]{0,79}\/(?:brand\.md|style\.json)|output-profiles\/[a-z0-9][a-z0-9_-]{0,79}\.json)$/.test(e.documentPath)) details.documentPath = e.documentPath;
@@ -204281,8 +204382,8 @@ function safeDiagnosticDetails(body) {
204281
204382
  if (e.code === "studio_invalid_input") {
204282
204383
  const allowed = /* @__PURE__ */ new Set(["tool", "projectId", "preferenceOverrideReason", "assetId", "language", "prompt", "referenceAssetIds", "quality", "resolution", "aspectRatio", "durationSeconds", "character", "text", "voice", "quoteId", "maxCredits", "userConfirmed", "batchLeaseToken", "request"]);
204283
204384
  if (typeof e.invalidFields === "string" && e.invalidFields.length <= 512) {
204284
- const fields2 = e.invalidFields.split(",").filter((f) => allowed.has(f));
204285
- if (fields2.length) details.invalidFields = [...new Set(fields2)].join(",");
204385
+ const fields3 = e.invalidFields.split(",").filter((f) => allowed.has(f));
204386
+ if (fields3.length) details.invalidFields = [...new Set(fields3)].join(",");
204286
204387
  }
204287
204388
  if (Number.isSafeInteger(e.issueCount) && Number(e.issueCount) > 0 && Number(e.issueCount) <= 1e3) details.issueCount = Number(e.issueCount);
204288
204389
  }
@@ -204301,7 +204402,7 @@ var ApiError = class extends CliError {
204301
204402
  const recovery2 = diagnostic ? recoveryGuidance(diagnostic.serviceCode, status) : void 0;
204302
204403
  const details = diagnostic ? safeDiagnosticDetails(body) : {};
204303
204404
  const preferenceHint = diagnostic?.serviceCode === "studio_preference_conflict" && details.conflict === "narration" ? 'Read workflow and the returned projectPath/documentPath. Only after an explicit user request, save narrationOverride={value:"voiceover",reason:"user-requested reason"} in this project.json, then choose an authorized public voice with studio voices and studio voice VOICE_ID --project ID --expected-revision N. Preserve the brand. Quote again; a preference exception never authorizes spending.' : diagnostic?.serviceCode === "studio_preference_conflict" && details.conflict === "voice_selection" ? "Read workflow and studio voice --project ID. Reconcile the requested public alias with the authorized saved voice using studio voices; a deliberate change uses studio voice VOICE_ID --project ID --expected-revision N. Preserve original/no-narration restrictions and the brand. Quote again; a voice selection never authorizes spending." : void 0;
204304
- const message = diagnostic?.serviceCode === "brand_limit_reached" ? `Este espacio alcanz\xF3 su l\xEDmite de marcas${typeof details.used === "number" && typeof details.limit === "number" ? ` (${details.used}/${details.limit})` : ""}.` : `API request failed (HTTP ${status}).`;
204405
+ const message = diagnostic?.serviceCode === "review_required" ? "The required visual presentation or approval is not recorded for this project context." : diagnostic?.serviceCode === "brand_limit_reached" ? `Este espacio alcanz\xF3 su l\xEDmite de marcas${typeof details.used === "number" && typeof details.limit === "number" ? ` (${details.used}/${details.limit})` : ""}.` : `API request failed (HTTP ${status}).`;
204305
204406
  super(diagnostic?.code ?? code, message, recovery2 ? recoveryHint(recovery2) : preferenceHint ?? diagnostic?.hint ?? hint, !diagnostic && safeToRetry && (status === 429 || status >= 500), { status, ...recovery2 ? { recovery: recovery2 } : {}, ...diagnostic ? { serviceCode: diagnostic.serviceCode, ...details } : {}, ...retryAfterMs === void 0 ? {} : { retryAfterMs } });
204306
204407
  this.status = status;
204307
204408
  this.body = body;
@@ -204490,7 +204591,7 @@ var Client = class {
204490
204591
  const retryAfterMs = retryDelay(response.headers.get("Retry-After"), this.runtime.now());
204491
204592
  if (!response.ok) {
204492
204593
  let errorBody;
204493
- if ((/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches|render-cloud|resources)(?:\/|\?|$)/.test(path) || path.startsWith("/v1/documents/") || path === "/v1/search/brief" || path === "/v1/projects" || /^\/v1\/projects\/[^/]+\/(?:progress|intake|resolve|export)$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
204594
+ if ((/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches|render-cloud|resources)(?:\/|\?|$)/.test(path) || path.startsWith("/v1/documents/") || path === "/v1/search/brief" || path === "/v1/projects" || /^\/v1\/projects\/[^/]+\/(?:progress|intake|resolve|export|review-evidence(?:\/[a-f0-9-]{36})?|continuity(?:\?.*)?)$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
204494
204595
  try {
204495
204596
  const parsed = await boundedJson(response, 16 * 1024);
204496
204597
  const knownDiagnostic = searchDiagnostic(response.status, parsed);
@@ -204543,12 +204644,12 @@ var Client = class {
204543
204644
  }
204544
204645
  }
204545
204646
  async uploadPreview(path, content, mimeType) {
204546
- const hash11 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
204547
- if (!hash11 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
204647
+ const hash13 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
204648
+ if (!hash13 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
204548
204649
  const sourceHash = new URL(path, this.url).searchParams.get("sourceSha256");
204549
- if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash11)) throw new Error("Use a distinct original SHA-256, or omit it.");
204650
+ if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash13)) throw new Error("Use a distinct original SHA-256, or omit it.");
204550
204651
  let plan;
204551
- const params = new URLSearchParams({ sha256: hash11, bytes: String(content.byteLength) });
204652
+ const params = new URLSearchParams({ sha256: hash13, bytes: String(content.byteLength) });
204552
204653
  const projectId = new URL(path, "https://local.invalid").searchParams.get("projectId");
204553
204654
  if (projectId) params.set("projectId", projectId);
204554
204655
  try {
@@ -204560,7 +204661,7 @@ var Client = class {
204560
204661
  if (typeof plan.allowed !== "boolean" || !Number.isSafeInteger(plan.additionalBytes)) throw new Error("Invalid preview preflight response.");
204561
204662
  if (plan.existingAsset) {
204562
204663
  const asset = plan.existingAsset;
204563
- if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash11 || asset.sha256 !== hash11 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
204664
+ if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash13 || asset.sha256 !== hash13 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
204564
204665
  return new Response(JSON.stringify({ ...asset, reused: true }), { headers: { "Content-Type": "application/json" } });
204565
204666
  }
204566
204667
  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.");
@@ -204848,12 +204949,12 @@ async function pushStyle(client, directory, id4, options = {}) {
204848
204949
  skippedResources.push({ id: resource.id, path, required: resource.required, reason: "Unsupported file type; retained as a local dependency, not uploaded." });
204849
204950
  continue;
204850
204951
  }
204851
- const bytes = await readReviewFile(await checkedPath(root, path, false), MAX), hash11 = digest4(bytes);
204852
- if (resource.source.sha256 && resource.source.sha256 !== hash11) throw new Error(`Hash mismatch: ${path}`);
204952
+ const bytes = await readReviewFile(await checkedPath(root, path, false), MAX), hash13 = digest4(bytes);
204953
+ if (resource.source.sha256 && resource.source.sha256 !== hash13) throw new Error(`Hash mismatch: ${path}`);
204853
204954
  assertPortableStyleCode(bytes, path);
204854
204955
  const ext = posix3.extname(path).toLowerCase(), name = "asset-" + posix3.basename(path, ext).replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 80) + ext;
204855
- uploads.push({ resource, path, hash: hash11, mime: mime2, name });
204856
- resource.source = { type: "asset", assetId: hash11, fileName: name, originalPath: path };
204956
+ uploads.push({ resource, path, hash: hash13, mime: mime2, name });
204957
+ resource.source = { type: "asset", assetId: hash13, fileName: name, originalPath: path };
204857
204958
  }
204858
204959
  if (options.withResources && files[resourcePath]) files[resourcePath] = stableJson(manifest);
204859
204960
  const preview = await pushWorkspace(client, root, files, { dryRun: true });
@@ -204956,7 +205057,7 @@ var LOCAL_DOCUMENT_TREES = [".editorbrain", ".editorharness", "videos"];
204956
205057
  var errno = (error62) => error62.code;
204957
205058
  var object12 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
204958
205059
  var keys2 = (value, expected) => Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
204959
- var identifier9 = (value) => typeof value === "string" && /^[a-z0-9][a-z0-9_-]{0,79}$/.test(value);
205060
+ var identifier10 = (value) => typeof value === "string" && /^[a-z0-9][a-z0-9_-]{0,79}$/.test(value);
204960
205061
  var localPath = (value) => typeof value === "string" && value.length <= 4096 && isAbsolute(value) && resolve2(value) === value && !/[\x00-\x1f\x7f]/.test(value);
204961
205062
  var sameBinding = (left, right) => left === null ? right === null : right !== null && left.endpoint === right.endpoint && left.workspaceId === right.workspaceId;
204962
205063
  var sameIdentity = (left, right) => left.projectId === right.projectId && left.brandId === right.brandId && sameBinding(left.binding, right.binding);
@@ -204981,7 +205082,7 @@ function role(value = "work") {
204981
205082
  }
204982
205083
  function parseBinding(value) {
204983
205084
  if (value === null) return null;
204984
- if (!object12(value) || !keys2(value, ["endpoint", "workspaceId"]) || typeof value.endpoint !== "string" || value.endpoint.length > 2048 || !identifier9(value.workspaceId)) throw registryError();
205085
+ if (!object12(value) || !keys2(value, ["endpoint", "workspaceId"]) || typeof value.endpoint !== "string" || value.endpoint.length > 2048 || !identifier10(value.workspaceId)) throw registryError();
204985
205086
  try {
204986
205087
  if (normalizeUrl(value.endpoint) !== value.endpoint) throw registryError();
204987
205088
  } catch {
@@ -204995,7 +205096,7 @@ function parseRegistry(raw) {
204995
205096
  if (!object12(value) || !keys2(value, ["schemaVersion", "projects"]) || value.schemaVersion !== 1 || !Array.isArray(value.projects) || value.projects.length > MAX_REGISTRY_PROJECTS) throw registryError();
204996
205097
  const seen = /* @__PURE__ */ new Set();
204997
205098
  const projects = value.projects.map((entry) => {
204998
- if (!object12(entry) || !keys2(entry, ["root", "projectId", "brandId", "binding", "folders", "updatedAt", ...Object.hasOwn(entry, "activity") ? ["activity"] : []]) || !localPath(entry.root) || !identifier9(entry.projectId) || !identifier9(entry.brandId) || !object12(entry.folders) || !Object.keys(entry.folders).length || Object.keys(entry.folders).some((key2) => !ROLES.includes(key2)) || Object.values(entry.folders).some((path) => !localPath(path)) || !validTimestamp(entry.updatedAt)) throw registryError();
205099
+ if (!object12(entry) || !keys2(entry, ["root", "projectId", "brandId", "binding", "folders", "updatedAt", ...Object.hasOwn(entry, "activity") ? ["activity"] : []]) || !localPath(entry.root) || !identifier10(entry.projectId) || !identifier10(entry.brandId) || !object12(entry.folders) || !Object.keys(entry.folders).length || Object.keys(entry.folders).some((key2) => !ROLES.includes(key2)) || Object.values(entry.folders).some((path) => !localPath(path)) || !validTimestamp(entry.updatedAt)) throw registryError();
204999
205100
  const key = JSON.stringify([entry.root, entry.projectId]);
205000
205101
  if (seen.has(key)) throw registryError();
205001
205102
  seen.add(key);
@@ -205085,7 +205186,7 @@ async function localBinding(root) {
205085
205186
  try {
205086
205187
  const bindings = candidates.map((raw) => {
205087
205188
  const state = JSON.parse(raw);
205088
- if (!object12(state) || state.schemaVersion !== 1 || !object12(state.documents) || typeof state.endpoint !== "string" || !identifier9(state.workspaceId)) throw new Error();
205189
+ if (!object12(state) || state.schemaVersion !== 1 || !object12(state.documents) || typeof state.endpoint !== "string" || !identifier10(state.workspaceId)) throw new Error();
205089
205190
  return parseBinding({ endpoint: normalizeUrl(state.endpoint), workspaceId: state.workspaceId });
205090
205191
  });
205091
205192
  if (bindings.some((binding) => !sameBinding(binding, bindings[0]))) throw new Error();
@@ -205329,7 +205430,7 @@ async function recordProjectActivity(context, options) {
205329
205430
  }
205330
205431
 
205331
205432
  // packages/cli/src/style-operations.ts
205332
- var hash5 = (bytes) => createHash5("sha256").update(bytes).digest("hex");
205433
+ var hash6 = (bytes) => createHash5("sha256").update(bytes).digest("hex");
205333
205434
  var readJson = async (root, path) => JSON.parse((await readReviewFile(await checkedPath(root, path, false), 1024 * 1024)).toString("utf8"));
205334
205435
  var jsonLiteral = (value) => JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
205335
205436
  async function localStyle(root, id4) {
@@ -205357,9 +205458,9 @@ function bindingSpans(code, bindings, format = "html") {
205357
205458
  if (format === "javascript-module") {
205358
205459
  const tokens = javascriptLiteralTokens(code);
205359
205460
  for (const binding of bindings) {
205360
- const literal2 = JSON.stringify(binding.literal), matches = tokens.filter((token) => code.slice(token.start, token.end) === literal2);
205361
- if (matches.length !== binding.occurrences) throw new Error(`Binding ${binding.name}: expected ${binding.occurrences} exact JSON literal occurrences; found ${matches.length}. Use a dedicated configuration object in the module; comments and templates are not binding sites.`);
205362
- spans.push(...matches.map((token) => ({ ...token, binding })));
205461
+ const literal2 = JSON.stringify(binding.literal), matches2 = tokens.filter((token) => code.slice(token.start, token.end) === literal2);
205462
+ if (matches2.length !== binding.occurrences) throw new Error(`Binding ${binding.name}: expected ${binding.occurrences} exact JSON literal occurrences; found ${matches2.length}. Use a dedicated configuration object in the module; comments and templates are not binding sites.`);
205463
+ spans.push(...matches2.map((token) => ({ ...token, binding })));
205363
205464
  }
205364
205465
  spans.sort((a, b) => a.start - b.start);
205365
205466
  for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw new Error("Overlapping component bindings; use distinct configuration literals.");
@@ -205407,7 +205508,7 @@ async function extractComponent(directory, id4, componentId, scene, bindingsFile
205407
205508
  bindingSpans(code, bindings, sourceFormat);
205408
205509
  const manifest = JSON.parse(files[base + "resources.json"] ?? stableJson({ schemaVersion: 1, id: id4, resources: [] }));
205409
205510
  if (manifest.resources.some((r) => r.id === resourceId)) throw new Error("Component resource ID already exists.");
205410
- const digest7 = hash5(bytes), destination = `production-assets/styles/${id4}/${componentId}-${digest7}${posix4.extname(scene).toLowerCase()}`;
205511
+ const digest7 = hash6(bytes), destination = `production-assets/styles/${id4}/${componentId}-${digest7}${posix4.extname(scene).toLowerCase()}`;
205411
205512
  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: digest7 } });
205412
205513
  const style = JSON.parse(files[base + "style.json"]);
205413
205514
  style.components = [...(style.components ?? []).filter((c) => c.id !== componentId), { id: componentId, status: bindings.length ? "implemented" : "concept" }];
@@ -205423,7 +205524,7 @@ async function extractComponent(directory, id4, componentId, scene, bindingsFile
205423
205524
  if (error62.code !== "ENOENT") throw error62;
205424
205525
  }
205425
205526
  if (previousSource) {
205426
- if (hash5(previousSource) !== digest7) throw new Error("Existing component snapshot was modified.");
205527
+ if (hash6(previousSource) !== digest7) throw new Error("Existing component snapshot was modified.");
205427
205528
  } else await atomicWrite(root, destination, bytes, { document: false, overwrite: false });
205428
205529
  for (const path of Object.keys(changes)) {
205429
205530
  let current2;
@@ -205469,7 +205570,7 @@ async function prepareComponent(directory, id4, componentId, parameters, out) {
205469
205570
  const expected = resource.source.type === "asset" ? resource.source.assetId : resource.source.sha256;
205470
205571
  if (!expected) throw new Error("Component source must have a pinned hash.");
205471
205572
  const bytes = await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024);
205472
- if (hash5(bytes) !== expected) throw new Error("Component source SHA-256 mismatch.");
205573
+ if (hash6(bytes) !== expected) throw new Error("Component source SHA-256 mismatch.");
205473
205574
  assertPortableStyleCode(bytes, path);
205474
205575
  const code = bytes.toString(), values = await readJson(root, parameters);
205475
205576
  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(", ")}.`);
@@ -205545,7 +205646,7 @@ async function prepareComponent(directory, id4, componentId, parameters, out) {
205545
205646
  const expected2 = source2.source.type === "asset" ? source2.source.assetId : source2.source.type === "local" ? source2.source.sha256 : void 0;
205546
205647
  const dependency = await readReviewFile(await checkedPath(root, mapped, false), 90 * 1024 * 1024);
205547
205648
  if (!expected2 && sourceFormat === "javascript-module") throw new Error("Module dependency must have a pinned hash: " + original);
205548
- if (expected2 && hash5(dependency) !== expected2) throw new Error("Dependency hash mismatch: " + original);
205649
+ if (expected2 && hash6(dependency) !== expected2) throw new Error("Dependency hash mismatch: " + original);
205549
205650
  assertPortableStyleCode(dependency, mapped);
205550
205651
  let rebased = posix4.relative(posix4.dirname(out), mapped).split("/").map(encodeURIComponent).join("/");
205551
205652
  if (sourceFormat === "javascript-module" && !rebased.startsWith(".")) rebased = "./" + rebased;
@@ -205555,7 +205656,7 @@ async function prepareComponent(directory, id4, componentId, parameters, out) {
205555
205656
  for (const replacement of replacements) prepared = prepared.split(replacement.from).join(replacement.to);
205556
205657
  assertPortableStyleCode(Buffer.from(prepared), out);
205557
205658
  await atomicWrite(root, out, prepared, { document: false, overwrite: false, mode: 384 });
205558
- return { id: id4, componentId, out, sourceFormat, sourceSha256: expected, sha256: hash5(Buffer.from(prepared)), executed: false, rendered: false, warnings: [...new Set(warnings), "Review unbound pilot values and dependencies. This is a code adaptation, not a transfer quality or determinism certification."] };
205659
+ return { id: id4, componentId, out, sourceFormat, sourceSha256: expected, sha256: hash6(Buffer.from(prepared)), executed: false, rendered: false, warnings: [...new Set(warnings), "Review unbound pilot values and dependencies. This is a code adaptation, not a transfer quality or determinism certification."] };
205559
205660
  }
205560
205661
  async function testStyleTransfer(directory, id4, projectId) {
205561
205662
  const root = await ensureRoot(directory);
@@ -205620,7 +205721,7 @@ async function loadCaptionContext(directory, projectId, styleId2, embedFont = tr
205620
205721
  if (!resource || resource.kind !== "font" || resource.source.type === "requirement") throw new Error("Caption font resource is missing; declare and download the exact font.");
205621
205722
  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;
205622
205723
  const bytes = await readReviewFile(await checkedPath(root, path, false), 8 * 1024 * 1024);
205623
- if (!expected || hash5(bytes) !== expected) throw new Error("Caption font needs a verified SHA-256.");
205724
+ if (!expected || hash6(bytes) !== expected) throw new Error("Caption font needs a verified SHA-256.");
205624
205725
  const ext = posix4.extname(path).slice(1);
205625
205726
  if (!["woff", "woff2", "ttf", "otf"].includes(ext)) throw new Error("Unsupported caption font format.");
205626
205727
  fontDataUrl = `data:font/${ext};base64,${bytes.toString("base64")}`;
@@ -206281,7 +206382,7 @@ async function localRenderPreflight(root, flags, dependencies) {
206281
206382
  const destination = join5(temporary, filePath);
206282
206383
  await mkdir5(dirname6(destination), { recursive: true });
206283
206384
  const output3 = await open9(destination, "wx", 384);
206284
- const hash11 = createHash7("sha256"), buffer = Buffer.allocUnsafe(4 * 1024 * 1024);
206385
+ const hash13 = createHash7("sha256"), buffer = Buffer.allocUnsafe(4 * 1024 * 1024);
206285
206386
  let count2 = 0;
206286
206387
  try {
206287
206388
  for (; ; ) {
@@ -206290,13 +206391,13 @@ async function localRenderPreflight(root, flags, dependencies) {
206290
206391
  count2 += bytesRead;
206291
206392
  if (count2 > before.size) throw invalid3("An input changed during preflight.", pathDetail(filePath));
206292
206393
  const bytes = buffer.subarray(0, bytesRead);
206293
- hash11.update(bytes);
206394
+ hash13.update(bytes);
206294
206395
  await output3.writeFile(bytes);
206295
206396
  }
206296
206397
  } finally {
206297
206398
  await output3.close();
206298
206399
  }
206299
- const sha2562 = hash11.digest("hex"), after = await source2.stat();
206400
+ const sha2562 = hash13.digest("hex"), after = await source2.stat();
206300
206401
  if (count2 !== before.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw invalid3("An input changed during preflight.", pathDetail(filePath));
206301
206402
  if (typeof manifest.files[index] !== "string" && (entry.bytes !== count2 || entry.sha256 !== sha2562)) throw invalid3("A local input differs from the prepared manifest.", { failure: { stage: "input_validation", reason: "input_checksum_mismatch", detail: entry.bytes !== count2 ? "size_mismatch" : "checksum_mismatch", ...pathDetail(filePath) } });
206302
206403
  files.push({ ...entry, bytes: count2, sha256: sha2562 });
@@ -206324,6 +206425,143 @@ async function localRenderPreflight(root, flags, dependencies) {
206324
206425
 
206325
206426
  // packages/cli/src/cloud-render.ts
206326
206427
  import { readFile as readFile2, mkdir as mkdir6, open as open11, unlink as unlink7, lstat as lstat12 } from "node:fs/promises";
206428
+
206429
+ // packages/cli/src/project-sync.ts
206430
+ import { readdir as readdir5 } from "node:fs/promises";
206431
+ function projectPushScope(projectId) {
206432
+ assertIdentifier(projectId);
206433
+ return { kind: "project", projectId, prefix: `videos/${projectId}/`, sharedDependenciesIncluded: false };
206434
+ }
206435
+ async function readProjectDocuments(root, projectId) {
206436
+ const scope = projectPushScope(projectId);
206437
+ const files = /* @__PURE__ */ Object.create(null);
206438
+ async function walk(path) {
206439
+ const directory = await checkedPath(root, path, false);
206440
+ let entries;
206441
+ try {
206442
+ entries = await readdir5(directory, { withFileTypes: true });
206443
+ } catch (error62) {
206444
+ if (error62.code === "ENOENT") return;
206445
+ throw error62;
206446
+ }
206447
+ for (const entry of entries) {
206448
+ const child = `${path}/${entry.name}`;
206449
+ if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${child}`);
206450
+ if (entry.name.startsWith(".")) continue;
206451
+ if (entry.isDirectory()) {
206452
+ if (["assets", "renders"].includes(entry.name)) continue;
206453
+ await walk(child);
206454
+ } else if (entry.isFile() && /\.(json|md)$/.test(entry.name)) files[child] = await readText(root, child);
206455
+ }
206456
+ }
206457
+ await walk(scope.prefix.slice(0, -1));
206458
+ return files;
206459
+ }
206460
+
206461
+ // packages/cli/src/production-context.ts
206462
+ async function readProductionSnapshot(client, projectId) {
206463
+ const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
206464
+ const snapshot = result2.editorialSnapshot;
206465
+ 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((hash13) => typeof hash13 !== "string" || !/^[a-f0-9]{64}$/.test(hash13))) 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.");
206466
+ if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash13) => typeof hash13 !== "string" || !/^[a-f0-9]{64}$/.test(hash13)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
206467
+ return snapshot;
206468
+ }
206469
+ async function prepareProductionContext(root, projectId, client) {
206470
+ const resolved = await resolveProject(await readProjectWorkspace(root, projectId), projectId);
206471
+ const sourceKey = stableJson(await effectiveEditorialSourceHashes(resolved));
206472
+ let contextVersion;
206473
+ const remote = async () => {
206474
+ const snapshot = await readProductionSnapshot(client, projectId);
206475
+ const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
206476
+ 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.");
206477
+ return snapshot.contextVersion;
206478
+ };
206479
+ if (client) contextVersion = await remote();
206480
+ else contextVersion = await sha256(sourceKey);
206481
+ const validateContext = async () => {
206482
+ const localUnchanged = async () => stableJson(await effectiveEditorialSourceHashes(await resolveProject(await readProjectWorkspace(root, projectId), projectId))) === sourceKey;
206483
+ if (!await localUnchanged()) return false;
206484
+ if (!client) return true;
206485
+ try {
206486
+ if (await remote() !== contextVersion) return false;
206487
+ } catch (error62) {
206488
+ if (error62 instanceof CliError && error62.code === "PRODUCTION_CONTEXT_CONFLICT") return false;
206489
+ throw error62;
206490
+ }
206491
+ return localUnchanged();
206492
+ };
206493
+ return { resolved, contextVersion, validateContext, contextScope: client ? "local_and_remote" : "local_only" };
206494
+ }
206495
+
206496
+ // packages/cli/src/workflow-local-sync.ts
206497
+ async function projectLocalSync(client, root, projectId, remoteHashes, completeRemoteContext = false) {
206498
+ assertIdentifier(projectId);
206499
+ const result2 = { status: "unknown", basis: "unavailable", projectId, pending: [], unknown: [], remoteChanged: [], contextPending: [], contextDirty: [], checkpoint: "unknown", actions: [], remoteVerified: false, uploaded: false };
206500
+ let files;
206501
+ let contextPaths;
206502
+ let requiredPaths;
206503
+ try {
206504
+ const projectFiles = await readProjectDocuments(root, projectId);
206505
+ if (!projectFiles[`videos/${projectId}/project.json`]) return result2;
206506
+ const contextFiles = await readProjectWorkspace(root, projectId);
206507
+ const project2 = JSON.parse(projectFiles[`videos/${projectId}/project.json`]);
206508
+ requiredPaths = new Set(projectSources(project2));
206509
+ contextPaths = /* @__PURE__ */ new Set([...Object.keys(contextFiles), ...projectSources(project2), ...optionalProjectSources(project2)]);
206510
+ files = { ...contextFiles, ...projectFiles };
206511
+ } catch (error62) {
206512
+ if (error62.code === "ENOENT") return result2;
206513
+ throw error62;
206514
+ }
206515
+ const me = await client.me();
206516
+ const state = await loadSyncState(root, client.url, me.workspaceId);
206517
+ const prefix = `videos/${projectId}/`, checkpoint = `${prefix}checkpoint.json`;
206518
+ const hashes = Object.fromEntries(await Promise.all(Object.entries(files).map(async ([path, content]) => [path, await sha256(content)])));
206519
+ for (const [path, current2] of Object.entries(hashes)) {
206520
+ const baseline = state.documents[path]?.sha256, remote = remoteHashes?.[path];
206521
+ if (remote === current2) continue;
206522
+ if (baseline && current2 !== baseline) result2.pending.push(path);
206523
+ else if (completeRemoteContext && contextPaths.has(path)) result2.remoteChanged.push(path);
206524
+ else if (remote && baseline && remote !== baseline) result2.remoteChanged.push(path);
206525
+ else if (!baseline) result2.unknown.push(path);
206526
+ }
206527
+ for (const path of Object.keys(state.documents)) if (path.startsWith(prefix) && !hashes[path] && !path.includes("/style-snapshots/")) result2.unknown.push(path);
206528
+ for (const path of contextPaths) if (!hashes[path] && (requiredPaths.has(path) || state.documents[path] || remoteHashes?.[path]) && !result2.unknown.includes(path)) result2.unknown.push(path);
206529
+ for (const values of [result2.pending, result2.unknown, result2.remoteChanged]) values.sort();
206530
+ result2.contextPending = [...new Set([...result2.pending, ...result2.unknown, ...result2.remoteChanged].filter((path) => contextPaths.has(path)))].sort();
206531
+ result2.contextDirty = [...new Set([...result2.pending, ...result2.remoteChanged, ...result2.unknown.filter((path) => !!state.documents[path])].filter((path) => contextPaths.has(path)))].sort();
206532
+ result2.remoteVerified = !result2.unknown.length && !result2.remoteChanged.length && Object.keys(hashes).length > 0 && Object.entries(hashes).every(([path, hash13]) => remoteHashes?.[path] === hash13);
206533
+ result2.basis = remoteHashes ? "current_remote_and_baseline" : "last_sync_baseline";
206534
+ result2.status = result2.pending.length ? "pending" : result2.unknown.length || result2.remoteChanged.length || !result2.remoteVerified ? "unknown" : "in_sync";
206535
+ result2.checkpoint = !hashes[checkpoint] ? "missing" : result2.pending.includes(checkpoint) ? "pending" : remoteHashes?.[checkpoint] === hashes[checkpoint] ? "in_sync" : "unknown";
206536
+ const project = [...result2.pending, ...result2.unknown, ...result2.remoteChanged].filter((path) => path.startsWith(prefix));
206537
+ const shared2 = [...result2.pending, ...result2.unknown, ...result2.remoteChanged].filter((path) => !path.startsWith(prefix));
206538
+ if (project.length) result2.actions.push({ kind: "project_sync", command: `editorbrain push --project ${projectId} --dry-run`, paths: [...new Set(project)].sort() });
206539
+ if (shared2.length) result2.actions.push({ kind: "shared_context", command: "editorbrain status", paths: [...new Set(shared2)].sort() });
206540
+ return result2;
206541
+ }
206542
+ async function currentProjectLocalSync(client, root, projectId) {
206543
+ const localSync = await projectLocalSync(client, root, projectId);
206544
+ if (localSync.basis === "unavailable") return { localSync, contextVersion: null };
206545
+ const snapshot = await readProductionSnapshot(client, projectId);
206546
+ return { localSync: await projectLocalSync(client, root, projectId, snapshot.sourceHashes, true), contextVersion: snapshot.contextVersion };
206547
+ }
206548
+
206549
+ // packages/cli/src/render-workflow-context.ts
206550
+ async function assertCloudRenderLocalContext(client, root, manifest, jobId) {
206551
+ if (manifest.purpose === "preview") return;
206552
+ const { localSync } = await currentProjectLocalSync(client, root, manifest.projectId);
206553
+ if (!localSync.contextDirty.length) return;
206554
+ try {
206555
+ const job = await client.request(`/v1/render-cloud/${jobId}`);
206556
+ if (job.id !== jobId || job.projectId !== manifest.projectId || typeof job.status !== "string") throw new CliError("INVALID_RENDER_RESPONSE", "The existing render did not match this project and request.", "Inspect the same job ID before continuing; do not create a replacement.");
206557
+ return;
206558
+ } catch (error62) {
206559
+ if (!(error62 instanceof ApiError) || error62.status !== 404) throw error62;
206560
+ }
206561
+ throw new CliError("RENDER_CONTEXT_UNSYNCED", "Local editorial documents differ from the context approved in the cloud.", "Inspect localSync and run the scoped push dry-run before reconciling documents and review evidence. Preview rendering remains available. Nothing was uploaded, rendered or charged.", false, { localSync });
206562
+ }
206563
+
206564
+ // packages/cli/src/cloud-render.ts
206327
206565
  import { dirname as dirname8, basename, extname as extname2 } from "node:path";
206328
206566
  import { createHash as createHash8, randomUUID as randomUUID3 } from "node:crypto";
206329
206567
 
@@ -206386,7 +206624,7 @@ async function inspectRenderFile(path, label, onChunk, chunkBytes = RENDER_CHUNK
206386
206624
  try {
206387
206625
  const before = await handle.stat();
206388
206626
  if (!before.isFile() || before.size <= 0 || before.size > RENDER_LONG_MAX_BYTES) throw bad(`Invalid render file size or type: ${label}. Maximum ${RENDER_LONG_MAX_BYTES} bytes.`);
206389
- const buffer = Buffer.allocUnsafe(chunkBytes), hash11 = createHash8("sha256");
206627
+ const buffer = Buffer.allocUnsafe(chunkBytes), hash13 = createHash8("sha256");
206390
206628
  let bytes = 0, index = 0;
206391
206629
  while (bytes < before.size) {
206392
206630
  const expected = Math.min(buffer.length, before.size - bytes);
@@ -206397,13 +206635,13 @@ async function inspectRenderFile(path, label, onChunk, chunkBytes = RENDER_CHUNK
206397
206635
  filled += part.bytesRead;
206398
206636
  }
206399
206637
  const chunk = buffer.subarray(0, filled);
206400
- hash11.update(chunk);
206638
+ hash13.update(chunk);
206401
206639
  if (onChunk) await onChunk(chunk, index++);
206402
206640
  bytes += filled;
206403
206641
  }
206404
206642
  const after = await handle.stat();
206405
206643
  if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw bad(`Input changed while reading: ${label}. Cancel any pending upload and prepare again.`);
206406
- return { bytes, sha256: hash11.digest("hex") };
206644
+ return { bytes, sha256: hash13.digest("hex") };
206407
206645
  } finally {
206408
206646
  await handle.close();
206409
206647
  }
@@ -206516,7 +206754,7 @@ async function cloudRenderCommand(client, root, command, id4, flags) {
206516
206754
  }
206517
206755
  const temp = dest + "." + randomUUID3() + ".part";
206518
206756
  const handle = await open11(temp, "wx", 384);
206519
- const hash11 = createHash8("sha256");
206757
+ const hash13 = createHash8("sha256");
206520
206758
  let count2 = 0;
206521
206759
  try {
206522
206760
  for (let c = 0; c < o.chunks; c++) {
@@ -206524,10 +206762,10 @@ async function cloudRenderCommand(client, root, command, id4, flags) {
206524
206762
  const data = delivery ? await client.renderDeliveryChunk(`${endpoint2}/delivery/content`, start3, Math.min(o.bytes, start3 + RENDER_CHUNK_BYTES) - 1, o.bytes) : await client.renderChunk(`${endpoint2}/output/${c}`);
206525
206763
  if (data.length !== Math.min(RENDER_CHUNK_BYTES, o.bytes - count2)) throw bad("Unexpected output chunk size.");
206526
206764
  await handle.writeFile(data);
206527
- hash11.update(data);
206765
+ hash13.update(data);
206528
206766
  count2 += data.length;
206529
206767
  }
206530
- if (hash11.digest("hex") !== o.sha256) throw bad("Output checksum mismatch.");
206768
+ if (hash13.digest("hex") !== o.sha256) throw bad("Output checksum mismatch.");
206531
206769
  await publishDownloadedRender(handle, temp, dest);
206532
206770
  } catch (e) {
206533
206771
  await handle.close().catch(() => {
@@ -206626,6 +206864,7 @@ async function cloudRenderCommand(client, root, command, id4, flags) {
206626
206864
  }
206627
206865
  const maxCredits = flags["max-credits"] === void 0 ? void 0 : Number(flags["max-credits"]);
206628
206866
  if (maxCredits !== void 0 && (!Number.isFinite(maxCredits) || maxCredits < 0)) throw bad("--max-credits must be a nonnegative number.");
206867
+ await assertCloudRenderLocalContext(client, root, manifest, input2.id);
206629
206868
  for (const f of manifest.files) {
206630
206869
  if (f.sourceAssetId) continue;
206631
206870
  const info = await inspectRenderFile(await checkedPath(root, f.path, false), f.path);
@@ -206905,8 +207144,8 @@ async function probeLocalMedia(value) {
206905
207144
  if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
206906
207145
  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";
206907
207146
  const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
206908
- const hash11 = createHash9("sha256");
206909
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash11.update(chunk);
207147
+ const hash13 = createHash9("sha256");
207148
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash13.update(chunk);
206910
207149
  const after = await handle.stat();
206911
207150
  await assertNoMediaSymlinks(path);
206912
207151
  const current2 = await lstat13(path);
@@ -206931,7 +207170,7 @@ async function probeLocalMedia(value) {
206931
207170
  ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
206932
207171
  };
206933
207172
  });
206934
- return { path, sha256: hash11.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
207173
+ return { path, sha256: hash13.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
206935
207174
  } finally {
206936
207175
  await handle.close();
206937
207176
  }
@@ -206940,21 +207179,21 @@ async function probeLocalMedia(value) {
206940
207179
  // packages/cli/src/production-continuity-check.ts
206941
207180
  var obj2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
206942
207181
  var number5 = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
206943
- var hash6 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
207182
+ var hash7 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
206944
207183
  function validateContinuityInput(value) {
206945
207184
  const issues = [];
206946
207185
  if (!obj2(value)) throw new CliError("INVALID_REVIEW_INPUT", "Review input must be an object.", "Use the documented continuity schema.");
206947
207186
  const add = (s) => issues.push(s);
206948
- if (value.schemaVersion !== 1 || !hash6(value.artifactSha256)) add("schemaVersion: 1 and artifactSha256 (64 lowercase hex) are required.");
207187
+ if (value.schemaVersion !== 1 || !hash7(value.artifactSha256)) add("schemaVersion: 1 and artifactSha256 (64 lowercase hex) are required.");
206949
207188
  if (Object.keys(value).some((k) => !["schemaVersion", "artifactSha256", "cuts", "transcript", "geometry"].includes(k))) add("Unexpected top-level review field.");
206950
207189
  if (!value.cuts && !value.geometry) add("Provide cuts + transcript and/or geometry.");
206951
207190
  if (value.cuts || value.transcript) {
206952
- if (!obj2(value.cuts) || !hash6(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.");
207191
+ if (!obj2(value.cuts) || !hash7(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.");
206953
207192
  else value.cuts.parts.forEach((p, i) => {
206954
207193
  if (!obj2(p) || !["source", "final"].every((k) => Array.isArray(p[k]) && p[k].length === 2 && p[k].every(number5) && p[k][1] > p[k][0])) add(`cuts.parts[${i}]: expected source:[start,end], final:[start,end] in seconds.`);
206955
207194
  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.`);
206956
207195
  });
206957
- if (!obj2(value.transcript) || !hash6(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.");
207196
+ if (!obj2(value.transcript) || !hash7(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.");
206958
207197
  else value.transcript.words.forEach((w, i) => {
206959
207198
  if (!obj2(w) || typeof w.text !== "string" || w.text.length > 500 || !number5(w.start) || !number5(w.end) || w.end <= w.start) add(`transcript.words[${i}]: expected text,start,end in source seconds.`);
206960
207199
  });
@@ -207077,7 +207316,7 @@ async function loadContinuityInput(root, path) {
207077
207316
  }
207078
207317
 
207079
207318
  // packages/cli/src/project-variants.ts
207080
- import { mkdir as mkdir7, readdir as readdir5 } from "node:fs/promises";
207319
+ import { mkdir as mkdir7, readdir as readdir6 } from "node:fs/promises";
207081
207320
  import { createHash as createHash10 } from "node:crypto";
207082
207321
  async function projectVariants(directory, project, operation, id4, changes) {
207083
207322
  const root = await ensureRoot(directory);
@@ -207088,7 +207327,7 @@ async function projectVariants(directory, project, operation, id4, changes) {
207088
207327
  if (operation === "list") {
207089
207328
  let entries;
207090
207329
  try {
207091
- entries = await readdir5(await checkedPath(root, base, false), { withFileTypes: true });
207330
+ entries = await readdir6(await checkedPath(root, base, false), { withFileTypes: true });
207092
207331
  } catch (e) {
207093
207332
  if (e.code === "ENOENT") return { variants: [] };
207094
207333
  throw e;
@@ -207162,7 +207401,7 @@ async function projectVariants(directory, project, operation, id4, changes) {
207162
207401
 
207163
207402
  // packages/cli/src/project-disk.ts
207164
207403
  import { constants as constants9 } from "node:fs";
207165
- import { open as open13, readdir as readdir6, lstat as lstat14, copyFile, rename as rename3, unlink as unlink8, chmod as chmod2, utimes } from "node:fs/promises";
207404
+ import { open as open13, readdir as readdir7, lstat as lstat14, copyFile, rename as rename3, unlink as unlink8, chmod as chmod2, utimes } from "node:fs/promises";
207166
207405
  import { createHash as createHash11, randomUUID as randomUUID4 } from "node:crypto";
207167
207406
  import { dirname as dirname10, join as join6 } from "node:path";
207168
207407
  async function fingerprintFile(path) {
@@ -207170,18 +207409,18 @@ async function fingerprintFile(path) {
207170
207409
  try {
207171
207410
  const before = await h.stat();
207172
207411
  if (!before.isFile()) throw new Error("Expected a regular file.");
207173
- const hash11 = createHash11("sha256");
207412
+ const hash13 = createHash11("sha256");
207174
207413
  const buffer = Buffer.alloc(1024 * 1024);
207175
207414
  let offset = 0;
207176
207415
  while (offset < before.size) {
207177
207416
  const { bytesRead } = await h.read(buffer, 0, Math.min(buffer.length, before.size - offset), offset);
207178
207417
  if (!bytesRead) throw new Error("File changed while hashing.");
207179
- hash11.update(buffer.subarray(0, bytesRead));
207418
+ hash13.update(buffer.subarray(0, bytesRead));
207180
207419
  offset += bytesRead;
207181
207420
  }
207182
207421
  const after = await h.stat();
207183
207422
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new Error("File changed while hashing.");
207184
- return { sha256: hash11.digest("hex"), bytes: before.size, ino: before.ino, dev: before.dev, mtimeMs: before.mtimeMs, atimeMs: before.atimeMs, mode: before.mode };
207423
+ return { sha256: hash13.digest("hex"), bytes: before.size, ino: before.ino, dev: before.dev, mtimeMs: before.mtimeMs, atimeMs: before.atimeMs, mode: before.mode };
207185
207424
  } finally {
207186
207425
  await h.close();
207187
207426
  }
@@ -207195,7 +207434,7 @@ async function projectDisk(root, project) {
207195
207434
  if (depth > 16) throw new CliError("DISK_SCAN_LIMIT", "Project exceeds 16 directory levels.", "Inspect the project manually; nothing was removed.");
207196
207435
  let entries;
207197
207436
  try {
207198
- entries = await readdir6(await checkedPath(root, dir, false), { withFileTypes: true });
207437
+ entries = await readdir7(await checkedPath(root, dir, false), { withFileTypes: true });
207199
207438
  } catch (e) {
207200
207439
  if (e.code === "ENOENT") return;
207201
207440
  throw e;
@@ -207314,7 +207553,7 @@ var introductions = {
207314
207553
  checkpoint: "Usa --expected-checkpoint SHA256|none del \xFAltimo resume para proteger decisiones desde esa lectura. current toma el hash al iniciar este comando y detecta solo escrituras concurrentes durante esta invocaci\xF3n. --current-version, --primary-artifact, --dependency y --render-command conservan contexto t\xE9cnico portable; nunca ejecutan. Guarda el hito declarado y hashes en videos/ID/checkpoint.json. Las rutas son relativas a la carpeta registrada por rol o al workspace. Repite --done/--pending/--decision; sus listas reemplazan las anteriores. --primary-artifact y --dependency registran y verifican sus archivos sin repetir --artifact. --artifact reemplaza la lista base y a\xF1ade esas referencias expl\xEDcitas; omitirlo conserva los artefactos previos. Usa push expl\xEDcitamente para sincronizar el texto.",
207315
207554
  projects: "find/list buscan por nombre/tema, --brand, --since y --before (UTC ISO), con paginaci\xF3n y actividad real; find --local consulta el registro privado; --dir lo limita a un workspace registrado, sin red ni escaneo. link/unlink administran carpetas privadas locales; where ID las consulta y resume ID recupera el hito. create crea el proyecto remoto y su baseline local sin sobrescribir cambios; pin-style fija sus documentos de estilo por hash; intake devuelve su material y enlace privado de subida. Conserva el mismo ID para retomarlo. No inicia edici\xF3n, render ni gasto; un enlace de subida requiere iniciar sesi\xF3n.",
207316
207555
  styles: "Reglas preferred orientan decisiones por video; required expl\xEDcitas se verifican por separado. rules inspect muestra hashes, rules decisions guarda adaptaciones por proyecto. captions preview es local expl\xEDcito; export avisa p\xE9rdidas SRT/ASS. 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.",
207317
- production: "submit prepara y registra una muestra privada autorizada con recibo recuperable; --parent sustituye la pendiente anterior sin aprobar ni borrar comentarios. reviews devuelve revisions por compatibilidad. 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.",
207556
+ production: "present sin --file consulta evidencia/version; con --file registra solo una presentaci\xF3n que realmente entregaste al usuario: expectedVersion, evidenceId UUID, contextVersion, phase directions|review|delivery, presented:true y source revision o local. Un HTML local requiere el sidecar y medios verificados; nunca inferir aprobaci\xF3n por generar/abrir/subir. decision local requiere userConfirmed y direcci\xF3n elegida o approved:true; nube reutiliza la revisi\xF3n existente. withdraw retira evidencia solo tras instrucci\xF3n del usuario y conserva el historial. submit prepara y registra una muestra privada autorizada con recibo recuperable; --parent sustituye la pendiente anterior sin aprobar ni borrar comentarios. reviews devuelve revisions por compatibilidad. 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.",
207318
207557
  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.",
207319
207558
  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.",
207320
207559
  variants: "Variantes locales: reutilizan la edici\xF3n base y registran cambios de gancho/CTA sin duplicar medios ni modificar el proyecto original."
@@ -207337,14 +207576,14 @@ Usa --help despu\xE9s de un subcomando para ver su sintaxis.
207337
207576
  }
207338
207577
 
207339
207578
  // packages/cli/src/local-styles.ts
207340
- import { readdir as readdir7 } from "node:fs/promises";
207579
+ import { readdir as readdir8 } from "node:fs/promises";
207341
207580
  async function listLocalStyles(directory) {
207342
207581
  const root = await ensureRoot(directory), styles = [], issues = [];
207343
207582
  for (const prefix of [".editorbrain", ".editorharness"]) {
207344
207583
  const base = `${prefix}/styles`;
207345
207584
  let entries;
207346
207585
  try {
207347
- entries = await readdir7(await checkedPath(root, base, false), { withFileTypes: true });
207586
+ entries = await readdir8(await checkedPath(root, base, false), { withFileTypes: true });
207348
207587
  } catch (e) {
207349
207588
  if (e.code === "ENOENT") continue;
207350
207589
  throw e;
@@ -207404,7 +207643,7 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
207404
207643
  if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
207405
207644
  const temporary = join7(dirname11(target), `.eb-motion-${randomUUID5()}.tmp`);
207406
207645
  let handle;
207407
- const hash11 = createHash12("sha256");
207646
+ const hash13 = createHash12("sha256");
207408
207647
  let size = 0;
207409
207648
  try {
207410
207649
  await mkdir8(dirname11(target), { recursive: true });
@@ -207415,10 +207654,10 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
207415
207654
  if (done) break;
207416
207655
  size += value.length;
207417
207656
  if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
207418
- hash11.update(value);
207657
+ hash13.update(value);
207419
207658
  await handle.writeFile(value);
207420
207659
  }
207421
- if (size !== pin.bytes || hash11.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
207660
+ if (size !== pin.bytes || hash13.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
207422
207661
  await handle.sync();
207423
207662
  await handle.close();
207424
207663
  await checkedPath(root, out, false);
@@ -208709,7 +208948,7 @@ var mimeTypes = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "vide
208709
208948
  var fail = (message) => {
208710
208949
  throw new CliError("INVALID_RESOURCE", message, "Read editorbrain help and references/personal-resources.md. No upload or paid analysis is automatic.");
208711
208950
  };
208712
- function uuid5(value) {
208951
+ function uuid8(value) {
208713
208952
  if (!value || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)) fail("Provide a resource UUID.");
208714
208953
  return value;
208715
208954
  }
@@ -208754,7 +208993,7 @@ async function registerLocalResource(client, root, file2, options = {}) {
208754
208993
  return { id: id4, revision: result2.revision, reused: !!existing, mediaUploaded: false, contentReviewed: false, localMap: path, next: "Use resources get to check for an existing index; inspect only missing evidence. Registering bytes does not transcribe, analyze or approve them." };
208755
208994
  }
208756
208995
  async function locateLocalResource(client, root, id4) {
208757
- uuid5(id4);
208996
+ uuid8(id4);
208758
208997
  const [item, me] = await Promise.all([client.request("/v1/resources/" + id4), client.request("/v1/me")]);
208759
208998
  const namespace = (await sha256(client.url + "\n" + me.workspaceId)).slice(0, 32), path = `.editorbrain-local/resources/${namespace}/${id4}.json`;
208760
208999
  let mapping;
@@ -208786,7 +209025,7 @@ async function personalResourceCommand(client, root, command, arg, flags) {
208786
209025
  }
208787
209026
  return client.request("/v1/resources?" + params);
208788
209027
  }
208789
- const id4 = uuid5(arg), path = "/v1/resources/" + id4;
209028
+ const id4 = uuid8(arg), path = "/v1/resources/" + id4;
208790
209029
  if (command === "get") return client.request(path);
208791
209030
  if (command === "locate") return locateLocalResource(client, root, id4);
208792
209031
  if (command === "segments") {
@@ -208821,7 +209060,7 @@ async function personalResourceCommand(client, root, command, arg, flags) {
208821
209060
  if (!item2.resource.media) fail("Tempo requires original media.");
208822
209061
  if (item2.index && item2.index.method !== "tempo") fail("This resource has other evidence. Preserve it and merge transcript segments explicitly with resources index.");
208823
209062
  await locateLocalResource(client, root, id4);
208824
- const job = await client.request("/v1/studio/jobs/" + uuid5(flag(flags, "job", true)));
209063
+ const job = await client.request("/v1/studio/jobs/" + uuid8(flag(flags, "job", true)));
208825
209064
  if (!["scribe", "tempo"].includes(job.tool) || job.status !== "completed" || !job.assetId || !/^[a-f0-9]{64}$/.test(job.assetId)) fail("Choose an existing completed Tempo job; this command never runs or retries a paid job.");
208826
209065
  const transcript = await client.request("/v1/assets/" + job.assetId), mapping = await readProductionJson(root, flag(flags, "mapping", true));
208827
209066
  const index = indexFromTempo(transcript, item2.resource.media, mapping);
@@ -208844,11 +209083,32 @@ import { promisify as promisify2 } from "node:util";
208844
209083
  // packages/cli/src/agent-guidance.ts
208845
209084
  import { createHash as createHash14 } from "node:crypto";
208846
209085
  import { constants as constants11 } from "node:fs";
208847
- import { lstat as lstat16, open as open16, readdir as readdir8, rename as rename4 } from "node:fs/promises";
209086
+ import { lstat as lstat16, open as open16, readdir as readdir9, rename as rename4 } from "node:fs/promises";
208848
209087
  import { fileURLToPath } from "node:url";
208849
209088
 
208850
209089
  // packages/cli/src/agent-guidance-history.ts
208851
209090
  var VERIFIED_GUIDANCE_RELEASES = [
209091
+ {
209092
+ "version": "0.49.0",
209093
+ "archiveSha256": "d547230e888151ce6d41e9fc2b382b2562b11614a20c11db27ada51987f98544",
209094
+ "files": {
209095
+ "editorbrain/references/production-continuity.md": "ca27f7b10c7fcb230c4317e9dd7cdce8a8697775433e77c13be9dea692b825d3"
209096
+ }
209097
+ },
209098
+ {
209099
+ "version": "0.48.0",
209100
+ "archiveSha256": "c4f3c075b863c14e6bf01ab234d57c1de3eb97d4957850605ec63c89388e6af3",
209101
+ "files": {
209102
+ "editorbrain/SKILL.md": "a2d1afd5be9c046fd2e3cdb997333c31216f0c2acdbf7feee5e31f7a84ee1c2d",
209103
+ "editorbrain/AGENTS.md": "01e2b0b19df7be07a7dccef9b977aabb1f6975636338b67a7dd32c88be596b58",
209104
+ "editorbrain/references/starting-an-edit.md": "e27fc77256a31e31b8a1baeeaa233cdca013d462685f00f82cb762e5195ce7d4",
209105
+ "editorbrain/references/production-continuity.md": "622d37372ddadf132c917db483541478808f2059809269074bf9ed1507ab7d81",
209106
+ "editorbrain/references/production-and-review.md": "521c5f2f9ed7081b37e36241910789372dfaf66bf9af992b3086516331084bd1",
209107
+ "editorbrain/references/workspace-files.md": "2aa122599adafa1ab9f8b5969967a17742b52fe1daec77ad79160fc5ab6dc360",
209108
+ "editorbrain/references/cli-mcp.md": "88d829b847525fc7eeaf369db7c2acd2a4adf10f2c23e22f0dd7878d4cc2074f",
209109
+ "editorbrain/references/task-map.md": "279585f6098eb9c68ad30701b1117f2d763d3c4a885a6a1f5c1b2b2f92e32e1e"
209110
+ }
209111
+ },
208852
209112
  {
208853
209113
  "version": "0.47.1",
208854
209114
  "archiveSha256": "7150de5343210269c33fabf105493150611df9d1a6fcee53f45eab1865b3120d",
@@ -209979,7 +210239,7 @@ async function loadSkill(directory) {
209979
210239
  const files = /* @__PURE__ */ new Map();
209980
210240
  async function walk(path = "") {
209981
210241
  const location3 = path ? await checkedPath(root, path, false) : root;
209982
- const entries = await readdir8(location3, { withFileTypes: true });
210242
+ const entries = await readdir9(location3, { withFileTypes: true });
209983
210243
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
209984
210244
  const child = path ? `${path}/${entry.name}` : entry.name;
209985
210245
  if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed in bundled skill: ${child}`);
@@ -210114,7 +210374,7 @@ async function installAgentGuidance(directory, agent = "both") {
210114
210374
 
210115
210375
  // packages/cli/src/skill-installations.ts
210116
210376
  import { createHash as createHash15, randomUUID as randomUUID7 } from "node:crypto";
210117
- import { readFile as readFile4, readdir as readdir9 } from "node:fs/promises";
210377
+ import { readFile as readFile4, readdir as readdir10 } from "node:fs/promises";
210118
210378
  import { homedir as homedir2 } from "node:os";
210119
210379
  import { isAbsolute as isAbsolute2, join as join9 } from "node:path";
210120
210380
 
@@ -210244,13 +210504,13 @@ var probe = async (tool) => {
210244
210504
  var remoteOptions = { timeoutMs: 3e3, maxAttempts: 1 };
210245
210505
  var links = { credits: "https://editorbrain.com/app/billing", integrations: "https://editorbrain.com/app/integrations" };
210246
210506
  function studioSummary(value) {
210247
- const invalid13 = () => new CliError("INVALID_RESPONSE", "Respuesta de herramientas IA incompleta.", "Consulta editorbrain studio catalog; no inicies una generaci\xF3n con estado desconocido.");
210248
- if (!value || typeof value !== "object") throw invalid13();
210507
+ const invalid14 = () => new CliError("INVALID_RESPONSE", "Respuesta de herramientas IA incompleta.", "Consulta editorbrain studio catalog; no inicies una generaci\xF3n con estado desconocido.");
210508
+ if (!value || typeof value !== "object") throw invalid14();
210249
210509
  const data = value;
210250
- if (typeof data.balance !== "number" || !Number.isFinite(data.balance) || data.balance < 0 || typeof data.checkoutAvailable !== "boolean" || !Array.isArray(data.tools) || data.tools.length > 20) throw invalid13();
210510
+ if (typeof data.balance !== "number" || !Number.isFinite(data.balance) || data.balance < 0 || typeof data.checkoutAvailable !== "boolean" || !Array.isArray(data.tools) || data.tools.length > 20) throw invalid14();
210251
210511
  const names = { scribe: "tempo", tempo: "tempo", prism: "prism", vox: "vox", music: "aura", aura: "aura" };
210252
210512
  const tools = data.tools.map((item) => {
210253
- if (!item || typeof item !== "object" || typeof item.id !== "string" || !Object.hasOwn(names, item.id) || typeof item.available !== "boolean" || typeof item.canSpend !== "boolean") throw invalid13();
210513
+ if (!item || typeof item !== "object" || typeof item.id !== "string" || !Object.hasOwn(names, item.id) || typeof item.available !== "boolean" || typeof item.canSpend !== "boolean") throw invalid14();
210254
210514
  const reasons = [!item.available ? "unavailable" : null, !item.canSpend ? "permission_required" : null, data.balance === 0 ? "no_credits" : null].filter((reason) => reason !== null);
210255
210515
  return {
210256
210516
  id: names[item.id],
@@ -210260,7 +210520,7 @@ function studioSummary(value) {
210260
210520
  reasons
210261
210521
  };
210262
210522
  });
210263
- if (tools.length !== 4 || new Set(tools.map((tool) => tool.id)).size !== 4) throw invalid13();
210523
+ if (tools.length !== 4 || new Set(tools.map((tool) => tool.id)).size !== 4) throw invalid14();
210264
210524
  return {
210265
210525
  balance: data.balance,
210266
210526
  checkoutAvailable: data.checkoutAvailable,
@@ -210412,7 +210672,7 @@ async function listInstallations(registry2 = installationRegistry()) {
210412
210672
  if (error62.code === "ENOENT") return [];
210413
210673
  throw error62;
210414
210674
  }
210415
- const names = (await readdir9(root)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort();
210675
+ const names = (await readdir10(root)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort();
210416
210676
  if (names.length > 1e3) throw new Error("Too many registered installations. Update a specific directory.");
210417
210677
  const records = [];
210418
210678
  for (const name of names) {
@@ -210868,38 +211128,6 @@ async function projectIntakeCommand(client, command, argument, flags) {
210868
211128
  });
210869
211129
  }
210870
211130
 
210871
- // packages/cli/src/project-sync.ts
210872
- import { readdir as readdir10 } from "node:fs/promises";
210873
- function projectPushScope(projectId) {
210874
- assertIdentifier(projectId);
210875
- return { kind: "project", projectId, prefix: `videos/${projectId}/`, sharedDependenciesIncluded: false };
210876
- }
210877
- async function readProjectDocuments(root, projectId) {
210878
- const scope = projectPushScope(projectId);
210879
- const files = /* @__PURE__ */ Object.create(null);
210880
- async function walk(path) {
210881
- const directory = await checkedPath(root, path, false);
210882
- let entries;
210883
- try {
210884
- entries = await readdir10(directory, { withFileTypes: true });
210885
- } catch (error62) {
210886
- if (error62.code === "ENOENT") return;
210887
- throw error62;
210888
- }
210889
- for (const entry of entries) {
210890
- const child = `${path}/${entry.name}`;
210891
- if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${child}`);
210892
- if (entry.name.startsWith(".")) continue;
210893
- if (entry.isDirectory()) {
210894
- if (["assets", "renders"].includes(entry.name)) continue;
210895
- await walk(child);
210896
- } else if (entry.isFile() && /\.(json|md)$/.test(entry.name)) files[child] = await readText(root, child);
210897
- }
210898
- }
210899
- await walk(scope.prefix.slice(0, -1));
210900
- return files;
210901
- }
210902
-
210903
211131
  // packages/cli/src/project-resume.ts
210904
211132
  import { constants as constants14 } from "node:fs";
210905
211133
  import { lstat as lstat20, open as open19, readdir as readdir11 } from "node:fs/promises";
@@ -210907,28 +211135,36 @@ import { createHash as createHash17 } from "node:crypto";
210907
211135
  import { join as join12, resolve as resolve11 } from "node:path";
210908
211136
 
210909
211137
  // packages/cli/src/project-continuity.ts
210910
- var hash7 = external_exports.string().regex(/^[a-f0-9]{64}$/);
211138
+ var hash8 = external_exports.string().regex(/^[a-f0-9]{64}$/);
210911
211139
  var id3 = external_exports.string().min(1).max(80);
210912
211140
  var text11 = external_exports.string().max(12e3);
210913
211141
  var count = external_exports.number().int().nonnegative();
210914
- var uuid8 = external_exports.string().uuid();
211142
+ var uuid9 = external_exports.string().uuid();
211143
+ var readiness = external_exports.unknown().transform((value, ctx) => {
211144
+ try {
211145
+ return parseProjectReviewReadiness(value);
211146
+ } catch {
211147
+ ctx.addIssue({ code: "custom", message: "Invalid review readiness" });
211148
+ return external_exports.NEVER;
211149
+ }
211150
+ });
210915
211151
  var section = (value) => external_exports.discriminatedUnion("status", [
210916
211152
  external_exports.object({ status: external_exports.literal("available"), value }).strict(),
210917
211153
  external_exports.object({ status: external_exports.literal("unavailable"), reason: external_exports.enum(["not_authorized", "not_available", "read_failed"]) }).strict()
210918
211154
  ]);
210919
- var page = (item, limit) => external_exports.object({ items: external_exports.array(item).max(limit), limit: external_exports.literal(limit), complete: external_exports.boolean(), nextCursor: uuid8.nullable(), contextVersion: hash7 }).strict();
211155
+ var page = (item, limit) => external_exports.object({ items: external_exports.array(item).max(limit), limit: external_exports.literal(limit), complete: external_exports.boolean(), nextCursor: uuid9.nullable(), contextVersion: hash8 }).strict();
210920
211156
  var review = external_exports.object({
210921
- revisionId: uuid8,
211157
+ revisionId: uuid9,
210922
211158
  projectId: id3,
210923
- assetId: hash7,
210924
- assetSha256: hash7,
210925
- contextVersion: hash7,
211159
+ assetId: hash8,
211160
+ assetSha256: hash8,
211161
+ contextVersion: hash8,
210926
211162
  status: external_exports.enum(["pending", "approved", "changes_requested"]),
210927
211163
  approvedAt: text11.nullable(),
210928
211164
  approvalKind: external_exports.enum(["human", "agent_recorded"]).nullable(),
210929
211165
  staleReasons: external_exports.array(external_exports.object({ kind: external_exports.enum(["context_changed", "style_pin_changed", "shared_style_changed", "project_media_changed", "brand_changed", "project_document_changed", "resource_changed", "review_preferences_changed"]), path: external_exports.string().max(500).optional(), message: text11.optional() }).strict()).max(256).optional(),
210930
211166
  superseded: external_exports.boolean().optional(),
210931
- supersededByRevisionId: uuid8.nullable().optional(),
211167
+ supersededByRevisionId: uuid9.nullable().optional(),
210932
211168
  supersededAt: text11.nullable().optional(),
210933
211169
  needsReview: external_exports.boolean().optional(),
210934
211170
  createdAt: text11,
@@ -210938,15 +211174,15 @@ var review = external_exports.object({
210938
211174
  pendingFeedbackCount: count
210939
211175
  }).strict();
210940
211176
  var feedback = external_exports.object({
210941
- feedbackId: uuid8,
211177
+ feedbackId: uuid9,
210942
211178
  projectId: id3,
210943
- revisionId: uuid8,
211179
+ revisionId: uuid9,
210944
211180
  text: text11,
210945
211181
  target: external_exports.object({ startMs: count.optional(), endMs: count.optional(), segmentId: text11.optional() }).strict(),
210946
211182
  reviewerKind: external_exports.enum(["human", "agent_recorded"]),
210947
211183
  status: external_exports.literal("pending"),
210948
211184
  createdAt: text11,
210949
- resultRevisionId: uuid8.nullable(),
211185
+ resultRevisionId: uuid9.nullable(),
210950
211186
  resultNote: text11.nullable(),
210951
211187
  preservedElements: text11.nullable(),
210952
211188
  resolvedAt: text11.nullable(),
@@ -210957,15 +211193,16 @@ var progress = external_exports.object({
210957
211193
  projectId: id3,
210958
211194
  stage: external_exports.enum(["to_edit", "editing", "review", "completed"]),
210959
211195
  reason: text11,
210960
- version: hash7,
211196
+ version: hash8,
210961
211197
  updatedAt: text11.nullable(),
210962
211198
  pendingFeedbackCount: count,
210963
- latestReview: external_exports.object({ revisionId: uuid8, assetId: hash7, mimeType: text11, title: text11, available: external_exports.boolean(), stale: external_exports.boolean(), effectiveApproval: external_exports.boolean() }).strict().nullable(),
210964
- finalRevisionId: uuid8.nullable()
211199
+ latestReview: external_exports.object({ revisionId: uuid9, assetId: hash8, mimeType: text11, title: text11, available: external_exports.boolean(), stale: external_exports.boolean(), effectiveApproval: external_exports.boolean() }).strict().nullable(),
211200
+ finalRevisionId: uuid9.nullable(),
211201
+ readiness: readiness.optional()
210965
211202
  }).strict();
210966
- var studioJob = external_exports.object({ id: uuid8, projectId: id3, tool: text11, status: text11, contextVersion: hash7, assetIds: external_exports.array(hash7).max(100), error: text11.nullable(), credits: external_exports.number().nonnegative(), createdAt: text11, updatedAt: text11 }).strict();
211203
+ var studioJob = external_exports.object({ id: uuid9, projectId: id3, tool: text11, status: text11, contextVersion: hash8, assetIds: external_exports.array(hash8).max(100), error: text11.nullable(), credits: external_exports.number().nonnegative(), createdAt: text11, updatedAt: text11 }).strict();
210967
211204
  var renderJob = external_exports.object({
210968
- id: uuid8,
211205
+ id: uuid9,
210969
211206
  projectId: id3,
210970
211207
  status: text11,
210971
211208
  cleanupPending: external_exports.boolean(),
@@ -210973,28 +211210,28 @@ var renderJob = external_exports.object({
210973
211210
  creditState: text11,
210974
211211
  customerCreditsReserved: external_exports.number().nonnegative(),
210975
211212
  customerCreditsCharged: external_exports.number().nonnegative(),
210976
- output: external_exports.object({ sha256: hash7, bytes: count }).strict().nullable(),
210977
- delivery: external_exports.object({ state: text11, destination: text11, retention: text11, assetId: hash7.nullable(), sha256: hash7.nullable(), bytes: count.nullable(), expiresAt: count.nullable() }).strict().nullable()
211213
+ output: external_exports.object({ sha256: hash8, bytes: count }).strict().nullable(),
211214
+ delivery: external_exports.object({ state: text11, destination: text11, retention: text11, assetId: hash8.nullable(), sha256: hash8.nullable(), bytes: count.nullable(), expiresAt: count.nullable() }).strict().nullable()
210978
211215
  }).strict();
210979
211216
  var projectContinuitySchema = external_exports.object({
210980
211217
  schemaVersion: external_exports.literal(1),
210981
211218
  workspaceId: id3,
210982
211219
  projectId: id3,
210983
211220
  brandId: id3,
210984
- project: external_exports.object({ revision: count, sha256: hash7 }).strict(),
210985
- checkpoint: section(external_exports.object({ path: text11, revision: count, sha256: hash7 }).strict().nullable()),
210986
- context: external_exports.object({ contextVersion: hash7, reviewMode: external_exports.enum(["direct", "directions", "sample"]), sourceHashes: external_exports.record(external_exports.string().max(500), hash7) }).strict(),
211221
+ project: external_exports.object({ revision: count, sha256: hash8 }).strict(),
211222
+ checkpoint: section(external_exports.object({ path: text11, revision: count, sha256: hash8 }).strict().nullable()),
211223
+ context: external_exports.object({ contextVersion: hash8, reviewMode: external_exports.enum(["direct", "directions", "sample"]), sourceHashes: external_exports.record(external_exports.string().max(500), hash8) }).strict(),
210987
211224
  progress: section(progress),
210988
211225
  lastApprovedReview: section(review.nullable()),
210989
211226
  reviews: section(page(review, 100)),
210990
211227
  feedback: section(page(feedback, 100)),
210991
- batch: section(external_exports.object({ batchId: uuid8, name: text11, status: text11, styleMode: text11, queueState: text11, leaseExpiresAt: text11.nullable(), claimHeldByConnection: external_exports.boolean(), maxConcurrency: count, notice: text11 }).strict().nullable()),
211228
+ batch: section(external_exports.object({ batchId: uuid9, name: text11, status: text11, styleMode: text11, queueState: text11, leaseExpiresAt: text11.nullable(), claimHeldByConnection: external_exports.boolean(), maxConcurrency: count, notice: text11 }).strict().nullable()),
210992
211229
  jobs: external_exports.object({
210993
- studio: section(external_exports.object({ scope: external_exports.literal("current_connection"), items: external_exports.array(studioJob).max(30), limit: external_exports.literal(30), complete: external_exports.boolean(), nextCursor: uuid8.nullable() }).strict()),
211230
+ studio: section(external_exports.object({ scope: external_exports.literal("current_connection"), items: external_exports.array(studioJob).max(30), limit: external_exports.literal(30), complete: external_exports.boolean(), nextCursor: uuid9.nullable() }).strict()),
210994
211231
  render: section(external_exports.object({ scope: external_exports.literal("current_user"), items: external_exports.array(renderJob).max(30), limit: external_exports.literal(30), complete: external_exports.boolean(), nextCursor: external_exports.null() }).strict())
210995
211232
  }).strict(),
210996
211233
  storage: section(external_exports.object({ configured: external_exports.boolean(), accountRevision: count, projectRevision: count, effectivePreferences: renderPreferencesSchema, quotaChecked: external_exports.literal(false), spendingAuthorized: external_exports.literal(false) }).strict()),
210997
- assets: section(external_exports.object({ items: external_exports.array(external_exports.object({ id: hash7, sha256: hash7.nullable(), bytes: count.nullable(), mimeType: text11.nullable(), source: external_exports.enum(["project_media", "studio_output", "render_delivery"]), state: external_exports.enum(["catalogued", "unavailable"]) }).strict()).max(100), complete: external_exports.boolean(), limit: external_exports.literal(100), verification: external_exports.literal("catalog_only") }).strict()),
211234
+ assets: section(external_exports.object({ items: external_exports.array(external_exports.object({ id: hash8, sha256: hash8.nullable(), bytes: count.nullable(), mimeType: text11.nullable(), source: external_exports.enum(["project_media", "studio_output", "render_delivery"]), state: external_exports.enum(["catalogued", "unavailable"]) }).strict()).max(100), complete: external_exports.boolean(), limit: external_exports.literal(100), verification: external_exports.literal("catalog_only") }).strict()),
210998
211235
  remoteReadOnly: external_exports.literal(true),
210999
211236
  downloadedMedia: external_exports.literal(false),
211000
211237
  spentCredits: external_exports.literal(0)
@@ -211003,12 +211240,19 @@ var invalid4 = () => new CliError("INVALID_CONTINUITY_RESPONSE", "Remote continu
211003
211240
  async function readProjectContinuity(client, expected, options = {}) {
211004
211241
  for (const value2 of [expected.projectId, expected.brandId]) assertIdentifier(value2);
211005
211242
  if (!expected.workspaceId) throw invalid4();
211006
- const parsedOptions = external_exports.object({ reviewsAfter: uuid8.optional(), feedbackAfter: uuid8.optional(), studioAfter: uuid8.optional() }).strict().safeParse(options);
211243
+ const parsedOptions = external_exports.object({ reviewsAfter: uuid9.optional(), feedbackAfter: uuid9.optional(), studioAfter: uuid9.optional(), includeReviewEvidence: external_exports.literal("1").optional() }).strict().safeParse(options);
211007
211244
  if (!parsedOptions.success) throw invalid4();
211008
211245
  const params = new URLSearchParams(Object.entries(parsedOptions.data).filter((entry) => entry[1] !== void 0));
211009
211246
  let raw;
211010
211247
  try {
211011
- raw = await client.request(`/v1/projects/${encodeURIComponent(expected.projectId)}/continuity${params.size ? "?" + params.toString() : ""}`);
211248
+ const route = `/v1/projects/${encodeURIComponent(expected.projectId)}/continuity`;
211249
+ try {
211250
+ raw = await client.request(`${route}${params.size ? "?" + params.toString() : ""}`);
211251
+ } catch (error62) {
211252
+ if (!(error62 instanceof ApiError) || error62.status !== 400 || error62.body?.error?.code !== "invalid_continuity_cursor" || !params.has("includeReviewEvidence")) throw error62;
211253
+ params.delete("includeReviewEvidence");
211254
+ raw = await client.request(`${route}${params.size ? "?" + params.toString() : ""}`);
211255
+ }
211012
211256
  } catch (error62) {
211013
211257
  if (!(error62 instanceof ApiError) || error62.status !== 404) throw error62;
211014
211258
  const [me, document2] = await Promise.all([client.me(), client.get(`videos/${expected.projectId}/project.json`)]);
@@ -211027,6 +211271,7 @@ async function readProjectContinuity(client, expected, options = {}) {
211027
211271
  if (value.workspaceId !== expected.workspaceId || value.projectId !== expected.projectId || value.brandId !== expected.brandId || value.context.sourceHashes[`videos/${expected.projectId}/project.json`] !== value.project.sha256) throw invalid4();
211028
211272
  if (value.checkpoint.status === "available" && value.checkpoint.value && value.checkpoint.value.path !== `videos/${expected.projectId}/checkpoint.json`) throw invalid4();
211029
211273
  if (value.progress.status === "available" && value.progress.value.projectId !== expected.projectId) throw invalid4();
211274
+ if (value.progress.status === "available" && value.progress.value.readiness && (value.progress.value.readiness.projectId !== expected.projectId || value.progress.value.readiness.contextVersion !== value.context.contextVersion)) throw invalid4();
211030
211275
  if (value.lastApprovedReview.status === "available" && value.lastApprovedReview.value && value.lastApprovedReview.value.projectId !== expected.projectId) throw invalid4();
211031
211276
  for (const component of [value.reviews, value.feedback]) if (component.status === "available") {
211032
211277
  if (component.value.contextVersion !== value.context.contextVersion || component.value.items.some((item) => item.projectId !== expected.projectId) || component.value.complete !== (component.value.nextCursor === null)) throw invalid4();
@@ -211173,15 +211418,15 @@ async function verifyLocalFile(options) {
211173
211418
  entry = cached2;
211174
211419
  verification = "cached_stat";
211175
211420
  } else {
211176
- const hash11 = createHash16("sha256");
211421
+ const hash13 = createHash16("sha256");
211177
211422
  let bytes = 0n;
211178
211423
  for await (const chunk of handle.createReadStream({ autoClose: false })) {
211179
211424
  bytes += BigInt(chunk.length);
211180
211425
  if (bytes > before.size) throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", "The artifact changed while hashing.", "Wait for its writer to finish before retrying.");
211181
- hash11.update(chunk);
211426
+ hash13.update(chunk);
211182
211427
  }
211183
211428
  if (bytes !== before.size) throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", "The artifact changed while hashing.", "Wait for its writer to finish before retrying.");
211184
- entry = { scope, path: target, stat: stat2, sha256: hash11.digest("hex"), hashedAt: (/* @__PURE__ */ new Date()).toISOString() };
211429
+ entry = { scope, path: target, stat: stat2, sha256: hash13.digest("hex"), hashedAt: (/* @__PURE__ */ new Date()).toISOString() };
211185
211430
  verification = "fresh_sha256";
211186
211431
  }
211187
211432
  if (!sameProjectIdentity(identity, await getLocalProjectIdentity(identity.root, identity.projectId))) throw new CliError("PROJECT_LINK_STALE", "The project identity changed during verification.", "Verify the current workspace and project before retrying.");
@@ -211220,12 +211465,12 @@ async function checkpointFileHash(root, path) {
211220
211465
  try {
211221
211466
  const before = await handle.stat();
211222
211467
  if (!before.isFile()) throw new CliError("CHECKPOINT_ARTIFACT_INVALID", `Artifact ${path} must be a regular file.`, "Link its directory and select a concrete scene, render or source file.");
211223
- const hash11 = createHash17("sha256");
211468
+ const hash13 = createHash17("sha256");
211224
211469
  let bytes = 0;
211225
211470
  for await (const chunk of handle.createReadStream({ autoClose: false })) {
211226
211471
  bytes += chunk.length;
211227
211472
  if (bytes > before.size) throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", `Artifact ${path} changed while hashing.`, "Wait for the writer/render to finish before saving a checkpoint.");
211228
- hash11.update(chunk);
211473
+ hash13.update(chunk);
211229
211474
  }
211230
211475
  const after = await handle.stat();
211231
211476
  await checkedPath(root, path, false);
@@ -211233,7 +211478,7 @@ async function checkpointFileHash(root, path) {
211233
211478
  if (!current2.isFile() || bytes !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || before.ino !== current2.ino || before.dev !== current2.dev || current2.mtimeMs !== after.mtimeMs || current2.size !== after.size) {
211234
211479
  throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", `Artifact ${path} changed while hashing.`, "Wait for the writer/render to finish before saving a checkpoint.");
211235
211480
  }
211236
- return { sha256: hash11.digest("hex"), bytes };
211481
+ return { sha256: hash13.digest("hex"), bytes };
211237
211482
  } finally {
211238
211483
  await handle.close();
211239
211484
  }
@@ -211524,12 +211769,13 @@ async function resumeProject(client, projectId, directory, limits = artifactSear
211524
211769
  const identity = await client.me();
211525
211770
  const syncState = await loadSyncState(root, client.url, identity.workspaceId);
211526
211771
  const project = JSON.parse(currentFiles[`videos/${projectId}/project.json`]);
211527
- const remoteContinuity = await readProjectContinuity(client, { workspaceId: identity.workspaceId, projectId, brandId: project.brand });
211772
+ const remoteContinuity = await readProjectContinuity(client, { workspaceId: identity.workspaceId, projectId, brandId: project.brand }, { includeReviewEvidence: "1" });
211528
211773
  const remote = remoteContinuity.status === "available" ? remoteContinuity.value : null;
211529
211774
  if (remote && (remote.project.sha256 !== syncState.documents[`videos/${projectId}/project.json`]?.sha256 || remote.checkpoint.status === "available" && remote.checkpoint.value?.sha256 !== syncState.documents[path]?.sha256)) {
211530
211775
  throw new CliError("CONTINUITY_CHANGED", "The remote project or checkpoint changed after pull.", "Resume again before continuing. Local changes were preserved; nothing was executed.");
211531
211776
  }
211532
211777
  const remoteContextDifferences = remote ? [.../* @__PURE__ */ new Set([...Object.keys(currentHashes), ...Object.keys(remote.context.sourceHashes)])].filter((path2) => currentHashes[path2] !== remote.context.sourceHashes[path2]) : [];
211778
+ const localSync = await projectLocalSync(client, root, projectId, remote ? { ...remote.context.sourceHashes, ...remote.checkpoint.status === "available" && remote.checkpoint.value ? { [path]: remote.checkpoint.value.sha256 } : {} } : void 0);
211533
211779
  const cloudAssets = remote?.assets.status === "available" ? remote.assets.value.items : [];
211534
211780
  const renderJobs = remote?.jobs.render.status === "available" ? remote.jobs.render.value.items : [];
211535
211781
  const nowSeconds = Math.floor(Date.now() / 1e3);
@@ -211559,6 +211805,8 @@ async function resumeProject(client, projectId, directory, limits = artifactSear
211559
211805
  remoteContinuity,
211560
211806
  artifactAvailability,
211561
211807
  remoteContextDifferences,
211808
+ localSync,
211809
+ reviewReadiness: remote?.progress.status === "available" ? remote.progress.value.readiness ?? null : null,
211562
211810
  technicalStateNotice: "Cloud catalog metadata is not a downloaded/verified copy; saved render commands never run automatically.",
211563
211811
  continuity: checkpoint?.continuity ?? null,
211564
211812
  localActivity: links2?.activity ? { ...links2.activity, filesVerifiedByReceipt: false } : null,
@@ -211847,39 +212095,6 @@ async function generatePresenterMatte(options) {
211847
212095
  // packages/cli/src/sfx.ts
211848
212096
  import { readdir as readdir12, lstat as lstat21 } from "node:fs/promises";
211849
212097
  import { join as join16, extname as extname5, basename as basename3 } from "node:path";
211850
-
211851
- // packages/cli/src/production-context.ts
211852
- async function prepareProductionContext(root, projectId, client) {
211853
- const resolved = await resolveProject(await readProjectWorkspace(root, projectId), projectId);
211854
- const sourceKey = stableJson(await effectiveEditorialSourceHashes(resolved));
211855
- let contextVersion;
211856
- const remote = async () => {
211857
- const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
211858
- const snapshot = result2.editorialSnapshot;
211859
- 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((hash11) => typeof hash11 !== "string" || !/^[a-f0-9]{64}$/.test(hash11))) 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.");
211860
- if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash11) => typeof hash11 !== "string" || !/^[a-f0-9]{64}$/.test(hash11)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
211861
- const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
211862
- 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.");
211863
- return snapshot.contextVersion;
211864
- };
211865
- if (client) contextVersion = await remote();
211866
- else contextVersion = await sha256(sourceKey);
211867
- const validateContext = async () => {
211868
- const localUnchanged = async () => stableJson(await effectiveEditorialSourceHashes(await resolveProject(await readProjectWorkspace(root, projectId), projectId))) === sourceKey;
211869
- if (!await localUnchanged()) return false;
211870
- if (!client) return true;
211871
- try {
211872
- if (await remote() !== contextVersion) return false;
211873
- } catch (error62) {
211874
- if (error62 instanceof CliError && error62.code === "PRODUCTION_CONTEXT_CONFLICT") return false;
211875
- throw error62;
211876
- }
211877
- return localUnchanged();
211878
- };
211879
- return { resolved, contextVersion, validateContext, contextScope: client ? "local_and_remote" : "local_only" };
211880
- }
211881
-
211882
- // packages/cli/src/sfx.ts
211883
212098
  var localPath2 = (id4) => {
211884
212099
  sfxBankPath(id4);
211885
212100
  return `.editorbrain-local/sfx/${id4}.json`;
@@ -212005,9 +212220,9 @@ async function prepareStudioAudio(root, file2, out, streamIndex) {
212005
212220
  const verified = await probeLocalMedia(prepared);
212006
212221
  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.");
212007
212222
  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.");
212008
- const bytes = await readFile8(prepared), hash11 = createHash18("sha256").update(bytes).digest("hex");
212223
+ const bytes = await readFile8(prepared), hash13 = createHash18("sha256").update(bytes).digest("hex");
212009
212224
  await link5(prepared, target);
212010
- return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash11, 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." };
212225
+ return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash13, 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." };
212011
212226
  } finally {
212012
212227
  await rm6(temp, { recursive: true, force: true });
212013
212228
  }
@@ -213216,7 +213431,7 @@ async function onboardingStatus(options) {
213216
213431
  var object15 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
213217
213432
  var integer2 = (value, min = 0) => Number.isSafeInteger(value) && Number(value) >= min;
213218
213433
  var text12 = (value, max) => typeof value === "string" && !!value.trim() && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
213219
- var hash8 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
213434
+ var hash9 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
213220
213435
  var date5 = (value) => text12(value, 64) && Number.isFinite(Date.parse(value));
213221
213436
  function invalidInput(message) {
213222
213437
  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.");
@@ -213233,7 +213448,7 @@ function validateInput(input2, accept = false) {
213233
213448
  if (!object15(input2) || Object.keys(input2).some((key) => !(accept ? ["brandId", "expectedDesignRevision", "runId", "reviewed"] : ["brandId", "expectedDesignRevision"]).includes(key))) throw invalidInput("Only the brand, document revision and explicit reviewed run are accepted.");
213234
213449
  brandId(input2.brandId);
213235
213450
  if (!integer2(input2.expectedDesignRevision, 1)) throw invalidInput("A positive source design revision is required.");
213236
- if (accept && (!hash8(input2.runId) || input2.reviewed !== true)) throw invalidInput("Accept only a specific proposal already reviewed and approved by the user; --run and --reviewed are required.");
213451
+ if (accept && (!hash9(input2.runId) || input2.reviewed !== true)) throw invalidInput("Accept only a specific proposal already reviewed and approved by the user; --run and --reviewed are required.");
213237
213452
  }
213238
213453
  function invalidResponse(write) {
213239
213454
  return new CliError(
@@ -213245,31 +213460,31 @@ function invalidResponse(write) {
213245
213460
  );
213246
213461
  }
213247
213462
  function brainState(value, brand, write = false) {
213248
- const invalid13 = () => {
213463
+ const invalid14 = () => {
213249
213464
  throw invalidResponse(write);
213250
213465
  };
213251
- if (!object15(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text12(value.notice, 2e3) || value.contextVersion !== void 0 && !hash8(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid13();
213466
+ if (!object15(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text12(value.notice, 2e3) || value.contextVersion !== void 0 && !hash9(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid14();
213252
213467
  let run2 = null;
213253
213468
  if (value.run !== null) {
213254
213469
  const row = value.run;
213255
- if (!object15(row) || !hash8(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer2(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer2(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date5(row.createdAt) || !date5(row.updatedAt)) return invalid13();
213256
- if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid13();
213470
+ if (!object15(row) || !hash9(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer2(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer2(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date5(row.createdAt) || !date5(row.updatedAt)) return invalid14();
213471
+ if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid14();
213257
213472
  let proposal = null;
213258
213473
  if (row.proposal !== null) {
213259
213474
  const proposed = row.proposal;
213260
- if (!object15(proposed) || !text12(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid13();
213475
+ if (!object15(proposed) || !text12(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid14();
213261
213476
  const recommendations = [];
213262
213477
  for (const item of proposed.recommendations) {
213263
- if (!object15(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text12(item.text, 500) || !text12(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) => !text12(field, 400))) return invalid13();
213478
+ if (!object15(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text12(item.text, 500) || !text12(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) => !text12(field, 400))) return invalid14();
213264
213479
  recommendations.push({ area: item.area, text: item.text, reason: item.reason, sourceFields: [...item.sourceFields] });
213265
213480
  }
213266
213481
  proposal = { summary: proposed.summary, recommendations };
213267
213482
  }
213268
- if ((row.status === "ready" || row.status === "accepted") && !proposal) return invalid13();
213483
+ if ((row.status === "ready" || row.status === "accepted") && !proposal) return invalid14();
213269
213484
  let usage = null;
213270
213485
  if (row.usage !== null) {
213271
213486
  const measured = row.usage;
213272
- if (!object15(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer2(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid13();
213487
+ if (!object15(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer2(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid14();
213273
213488
  usage = { inputTokens: measured.inputTokens, outputTokens: measured.outputTokens, totalTokens: measured.totalTokens, durationMs: measured.durationMs };
213274
213489
  }
213275
213490
  run2 = { id: row.id, status: row.status, proposal, usage, errorCode: row.errorCode, sourceDesignRevision: row.sourceDesignRevision, acceptedDesignRevision: row.acceptedDesignRevision, createdAt: row.createdAt, updatedAt: row.updatedAt };
@@ -213491,7 +213706,7 @@ async function loginWithDevice(options, overrides = {}) {
213491
213706
  import { chmod as chmod4, lstat as lstat26, mkdir as mkdir20, open as open23 } from "node:fs/promises";
213492
213707
  import { constants as constants18 } from "node:fs";
213493
213708
  import { homedir as homedir4 } from "node:os";
213494
- import { basename as basename8, dirname as dirname25, extname as extname10, join as join24, resolve as resolve19 } from "node:path";
213709
+ import { basename as basename9, dirname as dirname25, extname as extname11, join as join24, resolve as resolve19 } from "node:path";
213495
213710
 
213496
213711
  // packages/cli/src/direction-context.ts
213497
213712
  async function prepareDirectionContext(root, client, projectId) {
@@ -213557,8 +213772,8 @@ function parseAudioMeasurements(stderr, streamIndices, target) {
213557
213772
  blocks.set(index, [...blocks.get(index) ?? [], block]);
213558
213773
  }
213559
213774
  return streamIndices.map((streamIndex) => {
213560
- const matches = blocks.get(streamIndex);
213561
- const block = matches?.length === 1 ? matches[0] : {};
213775
+ const matches2 = blocks.get(streamIndex);
213776
+ const block = matches2?.length === 1 ? matches2[0] : {};
213562
213777
  const integrated = measurement(block.input_i), peak = measurement(block.input_tp), range2 = measurement(block.input_lra);
213563
213778
  const known = integrated.state === "finite" && peak.state === "finite" && range2.state === "finite" && range2.value >= 0;
213564
213779
  const targetStatus = !known ? "incomplete" : !target ? "not_evaluated" : Math.abs(integrated.value - target.targetIntegratedLufs) <= target.toleranceLu + 1e-9 && peak.value <= target.maxTruePeakDbtp + 1e-9 ? "pass" : "fail";
@@ -213693,8 +213908,8 @@ function safeUrl(value, hosts) {
213693
213908
  function failure3(code, message) {
213694
213909
  return new CliError(code, message, "Use public search terms and supported providers. Retry provider failures later; verify item rights on the source page.", false);
213695
213910
  }
213696
- function classifyMediaSourceLicense(fields2) {
213697
- const evidence = Object.entries(fields2).flatMap(([field, value]) => texts3(value).map((value2) => ({ field, value: value2 }))).slice(0, 16);
213911
+ function classifyMediaSourceLicense(fields3) {
213912
+ const evidence = Object.entries(fields3).flatMap(([field, value]) => texts3(value).map((value2) => ({ field, value: value2 }))).slice(0, 16);
213698
213913
  const recognized = /* @__PURE__ */ new Set();
213699
213914
  let unsupported = false, url3 = null;
213700
213915
  for (const entry of evidence) {
@@ -213809,11 +214024,11 @@ function requiredRecord(value) {
213809
214024
  return value;
213810
214025
  }
213811
214026
  function result(provider, id4, title, sourceUrl, metadataUrl, retrieved) {
213812
- const identifier11 = plain(id4, 512), name = plain(title), page2 = safeUrl(sourceUrl, HOSTS[provider]);
213813
- if (!identifier11 || !name || !page2) return null;
214027
+ const identifier12 = plain(id4, 512), name = plain(title), page2 = safeUrl(sourceUrl, HOSTS[provider]);
214028
+ if (!identifier12 || !name || !page2) return null;
213814
214029
  return {
213815
214030
  provider,
213816
- id: identifier11,
214031
+ id: identifier12,
213817
214032
  title: name,
213818
214033
  sourceUrl: page2,
213819
214034
  metadataUrl,
@@ -213828,7 +214043,7 @@ function result(provider, id4, title, sourceUrl, metadataUrl, retrieved) {
213828
214043
  previewVerified: false
213829
214044
  };
213830
214045
  }
213831
- var identifier10 = (value) => typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,199}$/.test(value) ? value : null;
214046
+ var identifier11 = (value) => typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,199}$/.test(value) ? value : null;
213832
214047
  async function searchProvider(provider, query, limit, client, report) {
213833
214048
  const output3 = [];
213834
214049
  const add = (item) => {
@@ -213862,7 +214077,7 @@ async function searchProvider(provider, query, limit, client, report) {
213862
214077
  const url3 = endpoint("https://images-api.nasa.gov/search", { q: query, media_type: "image", page: "1", page_size: String(limit) });
213863
214078
  const data = await client.get(url3);
213864
214079
  for (const value of requiredList(record14(data.collection).items).slice(0, limit)) {
213865
- const entry = record14(value), metadata = record14(array3(entry.data)[0]), id4 = identifier10(metadata.nasa_id);
214080
+ const entry = record14(value), metadata = record14(array3(entry.data)[0]), id4 = identifier11(metadata.nasa_id);
213866
214081
  const item = result(provider, id4, metadata.title, id4 ? `https://images.nasa.gov/details/${encodeURIComponent(id4)}` : null, url3.href, retrieved);
213867
214082
  if (item) {
213868
214083
  item.author = firstText(metadata.photographer, metadata.secondary_creator);
@@ -213909,7 +214124,7 @@ async function searchProvider(provider, query, limit, client, report) {
213909
214124
  url3.searchParams.append("fl[]", "title");
213910
214125
  const data = await client.get(url3);
213911
214126
  for (const value of requiredList(record14(data.response).docs).slice(0, limit)) {
213912
- const summary2 = record14(value), id4 = identifier10(summary2.identifier);
214127
+ const summary2 = record14(value), id4 = identifier11(summary2.identifier);
213913
214128
  if (!id4) {
213914
214129
  add(null);
213915
214130
  continue;
@@ -217023,44 +217238,352 @@ async function verifyProduction(options) {
217023
217238
  return { report, summary: { ...summarizeProductionVerification(report), reportPath, reportSha256 }, reportPath, reportSha256 };
217024
217239
  }
217025
217240
 
217241
+ // packages/cli/src/production-present.ts
217242
+ import { basename as basename5, extname as extname8 } from "node:path";
217243
+ var invalid9 = (message) => new CliError("INVALID_PRESENTATION_EVIDENCE", message, "Read production present --help. Record only an artifact actually shared with the user; generation, upload and opening a server are not presentation or approval.");
217244
+ var hash10 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
217245
+ async function presentProduction(client, root, projectId, value) {
217246
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid9("Evidence must be a JSON object.");
217247
+ const { expectedVersion, ...input2 } = value;
217248
+ if (!hash10(expectedVersion)) throw invalid9("expectedVersion must be the version returned by GET /v1/projects/ID/review-evidence.");
217249
+ if (input2.projectId !== void 0 && input2.projectId !== projectId) throw invalid9("The evidence belongs to a different project.");
217250
+ let evidence;
217251
+ try {
217252
+ evidence = parseReviewEvidence({ ...input2, projectId });
217253
+ } catch (error62) {
217254
+ throw invalid9(error62.message);
217255
+ }
217256
+ if (evidence.source.kind === "local") {
217257
+ const source2 = evidence.source;
217258
+ if (extname8(source2.relativePath).toLowerCase() !== ".html") throw invalid9("Local presentation requires a generated review HTML and its identity sidecar. Cloud media uses its existing review revision.");
217259
+ const verified = await checkpointFileHash(root, source2.relativePath);
217260
+ if (!verified.bytes || verified.sha256 !== source2.sha256) throw invalid9("The local artifact bytes do not match source.sha256. Preserve the old evidence and create a new version for changed media.");
217261
+ let sidecar;
217262
+ try {
217263
+ sidecar = JSON.parse((await readReviewFile(await checkedPath(root, `${source2.relativePath}.review.json`, false), 64 * 1024)).toString());
217264
+ } catch (error62) {
217265
+ if (error62.code !== "ENOENT") throw error62;
217266
+ }
217267
+ if (!sidecar) throw invalid9("This HTML lacks its review identity sidecar. Generate a new version with production review-artifact; preserve the existing file.");
217268
+ {
217269
+ if (sidecar.kind !== "editorbrain.local-review" || sidecar.artifactId !== source2.artifactId || sidecar.html?.sha256 !== source2.sha256 || sidecar.html?.file !== source2.relativePath) throw invalid9("The local review sidecar does not match this exact artifact.");
217270
+ const html = await readReviewFile(await checkedPath(root, source2.relativePath, false), 2 * 1024 * 1024);
217271
+ if (await sha256(html.toString()) !== source2.sha256) throw invalid9("The artifact changed during presentation verification.");
217272
+ const matches2 = [...html.toString().matchAll(/<script id="review-data" type="application\/json">([\s\S]*?)<\/script>/g)];
217273
+ if (matches2.length !== 1) throw invalid9("This is not an identifiable EditorBrain review artifact.");
217274
+ let data;
217275
+ try {
217276
+ data = JSON.parse(matches2[0][1]);
217277
+ } catch {
217278
+ throw invalid9("The artifact identity JSON is invalid.");
217279
+ }
217280
+ const { artifactId: embeddedId, ...clean } = data;
217281
+ if (embeddedId !== source2.artifactId || await sha256(JSON.stringify(clean)) !== source2.artifactId || data.projectId !== projectId || data.contextVersion !== evidence.contextVersion || data.stage !== evidence.phase) throw invalid9("The immutable artifact belongs to a different project, context or phase, or lacks that identity.");
217282
+ for (const key of ["projectId", "contextVersion", "stage"]) if (sidecar[key] !== void 0 && sidecar[key] !== data[key]) throw invalid9("The sidecar identity conflicts with the immutable artifact.");
217283
+ if (!Array.isArray(sidecar.media) || !sidecar.media.length || sidecar.media.length > 3) throw invalid9("The local review must include verified visual media; text-only proposals are not visual evidence.");
217284
+ if (evidence.phase === "directions") {
217285
+ if (!Array.isArray(data.directions) || !data.directions.length || data.directions.some((direction) => !hash10(direction?.preview?.sha256) || !sidecar.media.some((entry) => entry.sha256 === direction.preview.sha256 && entry.uri === direction.preview.uri))) throw invalid9("Every proposed direction needs its own verified visual preview.");
217286
+ if (evidence.decision && "directionId" in evidence.decision && !data.directions.some((direction) => direction.id === evidence.decision.directionId)) throw invalid9("The selected direction does not exist in this artifact.");
217287
+ } else if (!hash10(data.video?.sha256) || !sidecar.media.some((entry) => entry.sha256 === data.video.sha256 && entry.uri === data.video.uri && ["video/mp4", "video/webm"].includes(entry.mimeType))) {
217288
+ throw invalid9("A review or delivery requires its exact video medium.");
217289
+ }
217290
+ for (const entry of sidecar.media) {
217291
+ if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${source2.relativePath}.media-`) || !hash10(entry.sha256)) throw invalid9("The local review contains an invalid media reference.");
217292
+ const match = /^([a-f0-9-]{36})\/([a-f0-9]{64})\.(mp4|webm|png|jpg|jpeg|webp)$/.exec(entry.file.slice(`${source2.relativePath}.media-`.length));
217293
+ const mime2 = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
217294
+ if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime2[match[3]] || entry.uri !== `${encodeURIComponent(basename5(source2.relativePath) + ".media-" + match[1])}/${match[2]}.${match[3]}`) throw invalid9("The review URI does not name the verified local medium. Preserve the original HTML and media mapping.");
217295
+ const media3 = await checkpointFileHash(root, entry.file);
217296
+ if (media3.sha256 !== entry.sha256 || media3.bytes !== entry.bytes) throw invalid9("A local review medium changed or is missing. Present a new verified artifact.");
217297
+ }
217298
+ }
217299
+ }
217300
+ const { localSync, contextVersion } = await currentProjectLocalSync(client, root, projectId);
217301
+ if (localSync.contextPending.length) throw new CliError("PRESENTATION_CONTEXT_UNSYNCED", "This folder has project or shared-context edits whose synchronization is not confirmed.", "Inspect the localSync paths and scoped dry-run, reconcile deliberately, then prepare/present the artifact for the current context. No documents or media were uploaded.", false, { localSync });
217302
+ if (contextVersion !== null && contextVersion !== evidence.contextVersion) throw new CliError("PRESENTATION_CONTEXT_UNSYNCED", "The presentation belongs to a different editorial context than the current project.", "Read current evidence and reconcile the exact artifact context. Use production present --project ID --id EVIDENCE_ID to inspect an existing historical receipt without transferring its approval.", false, { localSync, contextVersion });
217303
+ const { projectId: _projectId, ...body } = evidence;
217304
+ const response = await client.request(`/v1/projects/${encodeURIComponent(projectId)}/review-evidence`, { method: "POST", body: { ...body, expectedVersion } });
217305
+ const receipt = response.receipt?.evidence ?? (Array.isArray(response.evidence) ? response.evidence.find((fact) => fact?.evidence?.evidenceId === evidence.evidenceId)?.evidence : void 0);
217306
+ let exact = false;
217307
+ try {
217308
+ exact = JSON.stringify(parseReviewEvidence(receipt)) === JSON.stringify(evidence);
217309
+ } catch {
217310
+ }
217311
+ if (response.projectId !== projectId || !hash10(response.contextVersion) || !hash10(response.version) || !exact) throw new CliError("PRESENTATION_OUTCOME_UNKNOWN", "The presentation receipt could not be verified.", "Read production present --project ID --id EVIDENCE_ID before retrying. Never create another ID to conceal an uncertain write.", false, { evidenceId: evidence.evidenceId, outcome: "unknown" });
217312
+ return { ...response, localSync, rendered: false, uploaded: false, spentCredits: 0 };
217313
+ }
217314
+ async function readPresentationInput(root, file2) {
217315
+ return JSON.parse((await readReviewFile(await checkedPath(root, file2, false), 64 * 1024)).toString());
217316
+ }
217317
+ async function withdrawPresentation(client, projectId, evidenceId, expectedVersion, userConfirmed) {
217318
+ if (!/^[a-zA-Z0-9_-]{1,80}$/.test(projectId) || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(evidenceId) || !hash10(expectedVersion)) throw invalid9("Use a project ID, evidence UUID and current expectedVersion from production present.");
217319
+ if (!userConfirmed) throw new CliError("USER_CONFIRMATION_REQUIRED", "Withdrawing review evidence requires the user\u2019s explicit instruction.", "Use --user-confirmed only after the user withdraws that exact local decision/presentation. Existing history and files are preserved.");
217320
+ const response = await client.request(`/v1/projects/${encodeURIComponent(projectId)}/review-evidence/${evidenceId}`, { method: "DELETE", body: { expectedVersion } });
217321
+ const receipt = response.receipt ?? (Array.isArray(response.evidence) ? response.evidence.find((fact) => fact?.evidence?.evidenceId === evidenceId) : void 0);
217322
+ if (response.projectId !== projectId || !hash10(response.version) || receipt?.evidence?.evidenceId !== evidenceId || receipt.invalidated !== "revoked") throw new CliError("PRESENTATION_OUTCOME_UNKNOWN", "The withdrawal receipt could not be verified.", "Read production present --project ID --id EVIDENCE_ID before retrying. Preserve this evidenceId and existing files.", false, { evidenceId, outcome: "unknown" });
217323
+ return response;
217324
+ }
217325
+
217026
217326
  // packages/cli/src/review-artifact.ts
217027
217327
  import { lstat as lstat25, mkdir as mkdir18, link as link7, unlink as unlink14 } from "node:fs/promises";
217028
- import { basename as basename5, dirname as dirname24, extname as extname8, resolve as resolve18 } from "node:path";
217328
+ import { basename as basename6, dirname as dirname24, extname as extname9, resolve as resolve18 } from "node:path";
217029
217329
  import { createHash as createHash25, randomUUID as randomUUID10 } from "node:crypto";
217030
217330
 
217031
217331
  // packages/cli/src/review-artifact-html.ts
217032
217332
  import { createHash as createHash24 } from "node:crypto";
217333
+
217334
+ // packages/cli/src/review-artifact-design.ts
217335
+ var reviewArtifactCss = String.raw`
217336
+ *{box-sizing:border-box}
217337
+ [hidden]{display:none!important}
217338
+ :root{color-scheme:light;--paper:#F3EDE3;--surface:#FBF8F2;--ink:#29231F;--muted:#70635A;--line:#D9CDBF;--wine:#682E3B;--wine-hover:#51232E;--soft:#EFE2DE;--amber:#E89A4A;font-family:'Avenir Next',Manrope,ui-sans-serif,system-ui,-apple-system,sans-serif;color:var(--ink);background:var(--paper);font-size:15px;line-height:1.5}
217339
+ body{margin:0;min-width:280px;-webkit-font-smoothing:antialiased}
217340
+ button,input,textarea,select{font:inherit}
217341
+ button,a,summary{touch-action:manipulation}
217342
+ button{min-height:44px;padding:10px 16px;border:1px solid var(--line);border-radius:12px;background:var(--surface);color:var(--ink);cursor:pointer;font-weight:600;font-size:14px;line-height:1.35}
217343
+ button:hover:not(:disabled){background:#EDE3D6;border-color:#AC9686;transform:translateY(-1px)}
217344
+ button:disabled{opacity:.45;cursor:not-allowed}
217345
+ button.primary{background:var(--wine);color:#FFF9F0;border-color:var(--wine)}
217346
+ button.primary:hover:not(:disabled){background:var(--wine-hover);border-color:var(--wine-hover)}
217347
+ button.text-button{border-color:transparent;background:none;color:var(--wine);padding-inline:0;text-align:left}
217348
+ :focus-visible{outline:3px solid var(--wine);outline-offset:4px}
217349
+ ::selection{background:var(--wine);color:#FFF9F0}
217350
+ a{color:var(--wine);text-underline-offset:4px;overflow-wrap:anywhere}
217351
+ h1,h2,h3,p{margin-top:0}
217352
+ h1{font-size:16px;font-weight:650;letter-spacing:-.025em;line-height:1.35;margin-bottom:3px;overflow-wrap:anywhere}
217353
+ h2{font-size:clamp(24px,2.7vw,32px);line-height:1.2;letter-spacing:-.04em;font-weight:650;margin-bottom:10px}
217354
+ h3{font-size:18px;letter-spacing:-.02em;line-height:1.35;margin-bottom:8px}
217355
+ p{line-height:1.6}
217356
+ .muted{color:var(--muted);font-size:13px}
217357
+ .topbar{display:flex;align-items:center;gap:20px 30px;padding:20px clamp(18px,4vw,48px);border-bottom:1px solid var(--line);flex-wrap:wrap;background:var(--surface)}
217358
+ .brand{flex:0 0 auto;display:block;color:var(--ink)}
217359
+ .brand svg{width:150px;height:auto;display:block}
217360
+ .project-heading{border-left:1px solid var(--line);padding-left:24px;flex:1;min-width:160px}
217361
+ #version{font-size:12px;color:var(--muted)}
217362
+ .project-stages{display:flex;flex-wrap:wrap;list-style:none;margin:0;padding:0;gap:6px;font-size:12px;color:var(--muted)}
217363
+ .project-stages li{padding:6px 10px;border:1px solid transparent;border-radius:30px;white-space:nowrap}
217364
+ .project-stages li[aria-current=step]{border-color:var(--line);background:var(--paper);color:var(--wine);font-weight:700}
217365
+ .project-stages b{font-variant-numeric:tabular-nums;margin-right:5px;font-weight:500}
217366
+ .header-actions{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
217367
+ button.guide-button{display:inline-flex;align-items:center;gap:7px;min-height:38px;padding:8px 10px;background:transparent;border-color:transparent;color:var(--wine);font-size:12px;white-space:nowrap}
217368
+ .guide-button span{display:grid;place-items:center;width:18px;height:18px;border:1px solid currentColor;border-radius:50%;font-size:11px}
217369
+ .review-guide{max-width:min(560px,calc(100vw - 32px));width:100%;max-height:calc(100svh - 32px);margin:auto;overflow:auto;overscroll-behavior:contain;padding:26px;border:1px solid var(--line);border-radius:20px;background:var(--surface);color:var(--ink);box-shadow:0 24px 80px #29231F33}
217370
+ .review-guide::backdrop{background:#29231F85}
217371
+ .guide-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px}
217372
+ .guide-heading .eyebrow{margin:0}
217373
+ .guide-heading button{min-width:36px;min-height:36px;padding:3px 8px;border-color:transparent;background:transparent;font-size:24px;font-weight:400}
217374
+ .review-guide h2{font-size:25px;line-height:1.25;margin-bottom:10px}
217375
+ #guide-intro{font-size:14px;color:var(--muted);margin-bottom:20px}
217376
+ .guide-steps{counter-reset:guide;list-style:none;padding:0;margin:0 0 18px}
217377
+ .guide-steps li{counter-increment:guide;position:relative;padding-left:38px;margin-bottom:16px}
217378
+ .guide-steps li::before{content:counter(guide);position:absolute;left:0;top:0;width:25px;height:25px;display:grid;place-items:center;border-radius:50%;background:var(--soft);color:var(--wine);font-size:12px;font-weight:600}
217379
+ .guide-steps strong{font-size:14px;font-weight:650}
217380
+ .guide-steps p{margin:4px 0 0;font-size:13px;color:var(--muted);line-height:1.55}
217381
+ .guide-approval{font-size:13px;color:var(--wine);border-left:2px solid var(--wine);padding-left:12px}
217382
+ .guide-storage{padding:14px 16px;background:var(--paper);border-radius:12px;margin:18px 0}
217383
+ .guide-storage strong{font-size:13px}
217384
+ .guide-storage p{font-size:12px;line-height:1.55;color:var(--muted);margin:7px 0 0}
217385
+ #guide-close{width:100%;margin-top:2px}
217386
+ .context-help{border:0;padding:0;margin:0 0 16px}
217387
+ .context-help summary{color:var(--wine);font-size:12px;font-weight:500;min-height:24px}
217388
+ .context-help p{font-size:12px;color:var(--muted);line-height:1.6;margin:8px 0 0;max-width:620px}
217389
+ .shell{width:100%;max-width:1360px;margin:0 auto;padding:26px clamp(18px,4vw,48px) 40px}
217390
+ .utility{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:24px;font-size:12px;color:var(--muted);flex-wrap:wrap}
217391
+ .utility p{margin:0}
217392
+ .privacy-dot{width:6px;height:6px;display:inline-block;border-radius:50%;background:var(--wine);margin-right:7px}
217393
+ .eyebrow{font-size:10px;letter-spacing:.13em;text-transform:uppercase;font-weight:700;color:var(--wine);margin-bottom:10px}
217394
+ .section-intro{max-width:720px;margin-bottom:24px}
217395
+ .section-intro p:last-child{margin-bottom:0;color:var(--muted);font-size:15px}
217396
+ .wizard{display:flex;gap:14px;max-width:720px;margin-bottom:26px}
217397
+ .wizard button{display:flex;flex:1;align-items:center;gap:9px;border:0;border-top:3px solid var(--line);border-radius:0;padding:12px 0 0;text-align:left;background:transparent;color:var(--muted);font-size:13px;min-width:0;min-height:45px}
217398
+ .wizard button span{font-variant-numeric:tabular-nums}
217399
+ .wizard button[aria-current=step]{border-top-color:var(--wine);color:var(--wine)}
217400
+ .wizard button:hover:not(:disabled){background:transparent;transform:none;color:var(--wine)}
217401
+ .workspace{display:grid;grid-template-columns:minmax(0,1fr) minmax(260px,320px);align-items:start;gap:28px}
217402
+ .workspace.no-transcript{grid-template-columns:minmax(0,1fr);max-width:980px;margin-inline:auto}
217403
+ .preview{min-width:0}
217404
+ .media-meta{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:10px;flex-wrap:wrap}
217405
+ #media-quality{margin:0}
217406
+ .screen{display:flex;align-items:center;justify-content:center;overflow:hidden;min-height:190px;border:1px solid #29231F;border-radius:20px;background:#191511;box-shadow:0 8px 24px #29231F0B}
217407
+ .screen video{display:block;max-width:100%;width:100%;max-height:min(60svh,570px);object-fit:contain}
217408
+ .controls{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:10px 0 16px;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}
217409
+ .controls-actions{display:flex;gap:6px}
217410
+ .controls button{min-height:36px;padding:7px 10px;font-size:12px;background:transparent}
217411
+ .watch-actions{display:flex;gap:10px;flex-wrap:wrap;padding:16px 0;border-top:1px solid var(--line)}
217412
+ .watch-actions button{flex:1;min-width:150px}
217413
+ .watch-actions p{flex-basis:100%;margin:0;font-size:12px;color:var(--muted)}
217414
+ .transcript-panel{position:sticky;top:22px;min-width:0;border:1px solid var(--line);border-radius:16px;background:var(--surface);padding:18px}
217415
+ details{border-top:1px solid var(--line);padding-top:14px;margin-top:16px}
217416
+ summary{cursor:pointer;font-size:14px;line-height:1.6;font-weight:650;min-height:30px}
217417
+ .transcript-panel details{margin:0;padding:0;border:0}
217418
+ .transcript-panel p{margin:10px 0;font-size:12px}
217419
+ #phrases{max-height:410px;overflow-y:auto;padding:3px;margin-top:14px;scrollbar-width:thin;scrollbar-color:var(--line) transparent}
217420
+ #phrases article{padding:12px;margin-bottom:8px;border:1px solid transparent;border-left:3px solid transparent;border-radius:10px;background:var(--paper)}
217421
+ #phrases article.speaking{border-left-color:var(--wine);background:var(--soft)}
217422
+ #phrases article.removed{background:transparent;border-color:var(--line)}
217423
+ #phrases article>button:first-child{padding:0;min-height:35px;display:block;border:0;background:none;text-align:left;line-height:1.65;width:100%;font-weight:500;font-size:13px}
217424
+ #phrases article>button:last-child{margin-top:8px;padding:6px 9px;min-height:34px;font-size:11px}
217425
+ #phrases small{color:var(--muted);font-size:11px}
217426
+ #phrases p{overflow-wrap:anywhere}
217427
+ #show-cuts-label{display:flex;gap:9px;align-items:center;margin-top:12px;color:var(--muted);font-size:12px}
217428
+ .change-panel{margin-top:18px;padding:22px;border:1px solid var(--line);border-radius:18px;background:var(--surface)}
217429
+ .change-panel h3{margin-bottom:6px}
217430
+ .change-panel>p{margin-bottom:18px}
217431
+ fieldset{border:0;margin:0;padding:0;min-width:0}
217432
+ legend,label{font-size:13px;font-weight:600}
217433
+ .target{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:10px 0 16px}
217434
+ .target button{min-height:42px;font-size:12px;padding:9px 12px;font-weight:500}
217435
+ .target button[aria-pressed=true]{background:var(--soft);border-color:var(--wine);color:var(--wine)}
217436
+ #target{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}
217437
+ #clear-time{min-width:38px;padding-inline:8px}
217438
+ textarea{display:block;min-width:0;width:100%;min-height:110px;resize:vertical;background:#FFFDF8;border:1px solid #B8A898;border-radius:12px;padding:14px;color:var(--ink);font-size:14px;line-height:1.65;margin-top:9px}
217439
+ textarea::placeholder{color:#807268}
217440
+ .form-footer{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:12px;flex-wrap:wrap}
217441
+ #draft-count{font-size:11px;color:var(--muted)}
217442
+ .templates{border:0;padding:0;margin:14px 0 0}
217443
+ .template-groups{display:grid;grid-template-columns:1fr 1fr;gap:14px;padding-top:14px}
217444
+ .template-groups h4{font-size:11px;letter-spacing:.03em;color:var(--muted);margin:0 0 8px}
217445
+ .template-groups button{display:block;min-height:36px;padding:6px 9px;font-size:12px;font-weight:500;text-align:left;width:100%;margin:5px 0;background:var(--paper)}
217446
+ .change-actions{display:flex;justify-content:space-between;gap:12px;margin-top:18px;flex-wrap:wrap}
217447
+ .notice{border-radius:12px;border:1px solid #D9C1A9;background:#F5E7D6;padding:12px 16px;font-size:13px;margin-bottom:18px}
217448
+ .notice.error{background:#F7E6E0;border-color:#CB8E84;color:#812B2B}
217449
+ #markers{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px}
217450
+ #markers:empty{display:none}
217451
+ #markers button{padding:5px 9px;min-height:32px;font-size:11px;font-variant-numeric:tabular-nums}
217452
+ .comments{margin-top:20px}
217453
+ .comments summary{margin-bottom:12px}
217454
+ #notes{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,270px),1fr));gap:12px}
217455
+ #notes article{padding:16px;border:1px solid var(--line);border-radius:14px;background:var(--surface);overflow-wrap:anywhere;font-size:13px}
217456
+ #notes p{margin:9px 0 0;white-space:pre-wrap}
217457
+ .note-head{display:flex;align-items:center;justify-content:space-between;gap:10px}
217458
+ .note-head button{font-size:11px;padding:5px 8px;min-height:32px;background:transparent}
217459
+ .note-head button:last-child{color:var(--muted);border-color:transparent}
217460
+ #undo{margin-top:12px;font-size:12px}
217461
+ #notes-empty{font-size:13px;color:var(--muted)}
217462
+ .send-summary{display:flex;gap:16px;padding:20px 22px;background:var(--surface);border:1px solid var(--line);border-radius:16px;margin-bottom:22px;align-items:flex-start}
217463
+ .summary-symbol{width:38px;height:38px;border-radius:50%;background:var(--soft);color:var(--wine);display:grid;place-items:center;font-size:20px;flex:0 0 auto}
217464
+ .send-summary h3{margin-bottom:5px}
217465
+ .send-summary p{font-size:14px;color:var(--muted);margin:0;overflow-wrap:anywhere}
217466
+ .handoff{margin-top:24px;padding-top:22px;border-top:1px solid var(--line)}
217467
+ .handoff h2{font-size:24px}
217468
+ .handoff-steps{display:grid;grid-template-columns:1fr 1fr;gap:14px;list-style:none;padding:0;margin:18px 0}
217469
+ .handoff-steps li{border:1px solid var(--line);border-radius:16px;background:var(--surface);padding:22px;display:flex;flex-direction:column;gap:14px}
217470
+ .handoff-steps li:first-child{border-color:var(--wine)}
217471
+ .handoff-steps strong{font-size:16px;letter-spacing:-.02em}
217472
+ .handoff-steps .step-number{width:28px;height:28px;display:grid;place-items:center;border-radius:50%;font-size:12px;background:var(--soft);color:var(--wine)}
217473
+ .handoff-steps p{font-size:13px;color:var(--muted);margin:0}
217474
+ .handoff-steps button{min-height:50px;margin-top:auto}
217475
+ .handoff-steps .chat-label{margin-top:auto;padding:12px 14px;border-radius:10px;background:var(--paper);font-size:13px;color:var(--muted)}
217476
+ .handoff-options{display:flex;align-items:center;gap:18px;flex-wrap:wrap}
217477
+ .handoff-options button{font-size:13px}
217478
+ .handoff-options details{border:0;margin:0;padding:0;flex:1 1 100%}
217479
+ #request,#phone-request{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;min-height:180px}
217480
+ #status{font-size:13px;color:var(--wine);margin:18px 0 0;overflow-wrap:anywhere}
217481
+ #status:empty{display:none}
217482
+ .auxiliary{margin-top:26px;max-width:780px}
217483
+ .auxiliary details>p{font-size:13px;color:var(--muted);max-width:700px}
217484
+ #phone-copy{margin-top:3px}
217485
+ #phone-status{margin-bottom:0}
217486
+ .learning-section{margin-top:22px;background:var(--surface);padding:18px 22px;border-radius:16px;border:1px solid var(--line)}
217487
+ .learning-section>details{border:0;margin:0;padding:0}
217488
+ .learning-section p{font-size:13px;color:var(--muted)}
217489
+ #learning-options{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:16px}
217490
+ #learning-options article{border-top:1px solid var(--line);padding-top:16px}
217491
+ #learning-options label{display:flex;align-items:flex-start;gap:9px;font-size:14px}
217492
+ select{max-width:100%;width:100%;background:var(--paper);border:1px solid #B8A898;border-radius:10px;min-height:44px;padding:10px;color:var(--ink);font-size:13px}
217493
+ input[type=checkbox]{accent-color:var(--wine);width:16px;height:16px;flex-shrink:0;margin:3px 0 0}
217494
+ #direction-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,275px),1fr));gap:18px}
217495
+ .direction{display:flex;flex-direction:column;padding:12px 12px 18px;border:1px solid var(--line);background:var(--surface);border-radius:18px;position:relative;min-width:0}
217496
+ .direction.chosen{border-color:var(--wine);box-shadow:0 0 0 1px var(--wine)}
217497
+ .direction-media{position:relative;aspect-ratio:16/10;border-radius:11px;overflow:hidden;background:#191511;margin-bottom:16px}
217498
+ .direction-media img,.direction-media video{width:100%;height:100%;display:block;object-fit:contain}
217499
+ .direction .no-preview{height:100%;display:flex;flex-direction:column;gap:9px;align-items:center;justify-content:center;background:#EDE3D6;color:var(--muted);font-size:12px;padding:16px;text-align:center}
217500
+ .no-preview span:first-child{font:italic 32px/1 Georgia,serif;color:var(--wine)}
217501
+ .direction h3{margin:0 4px 7px;font-size:19px}
217502
+ .direction>p{margin:0 4px 18px;color:var(--muted);font-size:14px;flex:1;overflow-wrap:anywhere}
217503
+ .direction>.direction-choice{width:100%;margin-top:14px}
217504
+ .direction.chosen>.direction-choice{background:var(--wine);border-color:var(--wine);color:#FFF9F0}
217505
+ .chosen-label{position:absolute;top:10px;left:10px;background:var(--wine);color:#FFF9F0;padding:5px 10px;border-radius:20px;font-size:11px;pointer-events:none}
217506
+ .direction details{margin:0 4px;padding-top:10px}
217507
+ .direction details a{display:block;font-size:12px;margin:8px 0}
217508
+ footer{display:flex;justify-content:space-between;gap:12px;border-top:1px solid var(--line);margin-top:30px;padding-top:16px;color:var(--muted);font-size:11px;flex-wrap:wrap}
217509
+ .noscript{padding:18px;margin:18px;border:1px solid var(--line);border-radius:12px}
217510
+ @media(min-width:761px){.topbar{padding-block:14px}.shell{padding-top:18px}.utility{margin-bottom:12px}.wizard{margin-bottom:16px}.section-intro{margin-bottom:16px}.eyebrow{margin-bottom:6px}.section-intro h2{margin-bottom:6px}.media-meta{margin-bottom:8px}.screen video{max-height:min(52svh,max(180px,calc(100svh - 480px)),570px)}.controls{margin-top:8px;margin-bottom:10px}.watch-actions{padding-block:12px;gap:8px}}
217511
+ @media(max-width:950px){.header-actions{width:100%;justify-content:space-between;gap:4px 8px}.project-stages{justify-content:flex-start}.topbar{gap:16px;padding-block:16px}.workspace{grid-template-columns:minmax(0,1fr) 270px;gap:20px}.shell{padding-top:22px}.brand svg{width:132px}.project-heading{padding-left:18px}}
217512
+ @media(max-width:760px){.topbar{padding-inline:18px}.project-heading{min-width:120px}.shell{padding:20px 18px 28px}.utility{gap:6px;margin-bottom:20px}.workspace{grid-template-columns:1fr}.transcript-panel{position:static;padding:16px}.screen{min-height:150px;border-radius:14px}.screen video{max-height:49svh}.controls{margin-bottom:12px}.wizard{gap:10px;margin-bottom:22px}.wizard button{font-size:12px}.change-panel{padding:18px}.handoff-steps{grid-template-columns:1fr}.handoff-steps li{padding:18px}.handoff-steps li+li{gap:10px}.send-summary{padding:18px}.watch-actions button{min-width:120px}.learning-section{padding:18px}#phrases{max-height:260px}h2{font-size:26px}}
217513
+ @media(max-width:380px){.brand svg{width:110px}.topbar{gap:12px}.project-heading{padding-left:12px}.project-stages{gap:0;font-size:11px}.project-stages li{padding-inline:8px}.utility{font-size:11px}.template-groups{grid-template-columns:1fr}.target{gap:6px}.target button{padding:8px}.watch-actions{flex-direction:column}.controls{flex-wrap:wrap}.form-footer{align-items:stretch}.form-footer button{width:100%}.change-actions button{flex:1}}
217514
+ @media(prefers-reduced-motion:no-preference){button,.direction{transition:background .15s,border-color .15s,transform .15s}.step-content{animation:arrive .18s ease-out}@keyframes arrive{from{opacity:.6;transform:translateY(4px)}to{opacity:1;transform:none}}}
217515
+ `;
217516
+
217517
+ // packages/cli/src/review-artifact-html.ts
217033
217518
  function reviewApp() {
217034
217519
  const data = JSON.parse(document.getElementById("review-data").textContent);
217035
217520
  const $ = (id4) => document.getElementById(id4);
217036
217521
  const text15 = (tag, value, cls = "") => {
217037
- const e = document.createElement(tag);
217038
- e.textContent = value;
217039
- e.className = cls;
217040
- return e;
217522
+ const node2 = document.createElement(tag);
217523
+ node2.textContent = value;
217524
+ node2.className = cls;
217525
+ return node2;
217041
217526
  };
217042
- const button = (label, fn) => {
217043
- const e = text15("button", label);
217044
- e.type = "button";
217045
- e.onclick = fn;
217046
- return e;
217527
+ const button = (label, run2, cls = "") => {
217528
+ const node2 = text15("button", label, cls);
217529
+ node2.type = "button";
217530
+ node2.onclick = run2;
217531
+ return node2;
217047
217532
  };
217048
217533
  const time3 = (ms) => `${Math.floor(ms / 6e4).toString().padStart(2, "0")}:${(ms / 1e3 % 60).toFixed(1).padStart(4, "0")}`;
217049
- const status = (s) => {
217050
- $("status").textContent = s;
217534
+ const status = (message) => {
217535
+ $("status").textContent = message;
217051
217536
  };
217052
- let notes = [], choice = "", approval = false, mark, segmentId, endMs;
217537
+ let notes = [], choice = "", approval = false;
217538
+ let mark, segmentId, endMs;
217053
217539
  let learningChoices = {};
217054
- let removed, storageOk = true, restoredDraft = "";
217540
+ let removed, storageOk = true, restoredDraft = "", copied = false;
217541
+ let step = 1;
217055
217542
  const key = "editorbrain:review:" + data.artifactId;
217543
+ const note = $("note");
217544
+ const player = $("player");
217545
+ let mediaReady = false;
217546
+ const isDirections = data.stage === "directions";
217547
+ const isDelivery = data.stage === "delivery";
217548
+ const approvalReady = () => approval && mediaReady && !note.value.trim();
217549
+ const guide = $("review-guide");
217550
+ const guideButton = $("how-it-works");
217551
+ const guideSteps = isDirections ? [
217552
+ ["Mira las propuestas", "Compara las im\xE1genes o videos y la idea de cada direcci\xF3n."],
217553
+ ["Elige una direcci\xF3n", "Pulsa Elegir en la que prefieras. Puedes cambiar de elecci\xF3n."],
217554
+ ["Copia tu elecci\xF3n", "El mensaje incluye la propuesta y esta versi\xF3n."],
217555
+ ["P\xE9gala en el mismo chat", "Tu agente recibir\xE1 tu elecci\xF3n y podr\xE1 preparar la muestra."]
217556
+ ] : [
217557
+ ["Mira esta versi\xF3n", "Reproduce el video con audio antes de decidir."],
217558
+ ["Marca o comenta", "En Cambia, se\xF1ala un segundo con Marcar este momento o elige En todo el video."],
217559
+ ["Guarda tus comentarios", "Pulsa Guardar comentario en cada nota y revisa el resumen en Env\xEDa."],
217560
+ ["Copia y pega en tu chat", "Copia el mensaje y p\xE9galo en la misma conversaci\xF3n de Claude o Codex."]
217561
+ ];
217562
+ $("guide-title").textContent = isDirections ? "Elige la direcci\xF3n de tu video" : isDelivery ? "Revisa y aprueba la entrega" : "Revisa tu video sin complicarte";
217563
+ for (const [title, description] of guideSteps) {
217564
+ const item = text15("li", "");
217565
+ item.append(text15("strong", title), text15("p", description));
217566
+ $("guide-steps").append(item);
217567
+ }
217568
+ $("guide-approval").hidden = isDirections;
217569
+ $("guide-approval").textContent = isDelivery ? "Sin cambios: pulsa Aprobar esta entrega y copia la aprobaci\xF3n al chat." : "Sin cambios: pulsa Me gusta esta versi\xF3n y copia la aprobaci\xF3n al chat.";
217570
+ guideButton.onclick = () => {
217571
+ for (const video of Array.from(document.querySelectorAll("video"))) video.pause();
217572
+ if (!guide.open) guide.showModal();
217573
+ };
217574
+ $("guide-dismiss").onclick = () => guide.close();
217575
+ $("guide-close").onclick = () => guide.close();
217576
+ guide.onclose = () => guideButton.focus({ preventScroll: true });
217056
217577
  try {
217057
217578
  const saved = JSON.parse(localStorage.getItem(key) || "null");
217058
217579
  if (saved) {
217059
217580
  for (const proposal of data.learnings ?? []) {
217060
- const v = saved.learningChoices?.[proposal.id];
217061
- if (v && ["project", "style", "series", "format", "brand"].includes(v.target)) learningChoices[proposal.id] = { selected: v.selected === true, target: v.target };
217581
+ const value = saved.learningChoices?.[proposal.id];
217582
+ if (value && ["project", "style", "series", "format", "brand"].includes(value.target)) {
217583
+ learningChoices[proposal.id] = { selected: value.selected === true, target: value.target };
217584
+ }
217062
217585
  }
217063
- notes = Array.isArray(saved.notes) ? saved.notes.filter((n) => n && typeof n.id === "string" && typeof n.text === "string" && n.text.length <= 1500 && [n.startMs, n.endMs].every((t) => t === void 0 || Number.isFinite(t) && t >= 0 && t <= 36e6) && [n.segmentId].every((t) => t === void 0 || typeof t === "string")).slice(0, 100) : [];
217586
+ notes = Array.isArray(saved.notes) ? saved.notes.filter((n) => n && typeof n.id === "string" && typeof n.text === "string" && n.text.length <= 1500 && [n.startMs, n.endMs].every((t) => t === void 0 || Number.isFinite(t) && t >= 0 && t <= 36e6) && (n.segmentId === void 0 || typeof n.segmentId === "string")).slice(0, 100) : [];
217064
217587
  choice = data.directions?.some((d) => d.id === saved.choice) ? saved.choice : "";
217065
217588
  approval = saved.approval === true && !notes.length;
217066
217589
  restoredDraft = typeof saved.draft === "string" && saved.draft.length <= 1500 ? saved.draft : "";
@@ -217069,155 +217592,224 @@ function reviewApp() {
217069
217592
  endMs = Number.isFinite(saved.endMs) && saved.endMs >= 0 ? saved.endMs : void 0;
217070
217593
  segmentId = typeof saved.segmentId === "string" ? saved.segmentId : void 0;
217071
217594
  }
217595
+ if ([1, 2, 3].includes(saved.step)) step = saved.step;
217596
+ else if (notes.length || restoredDraft) step = 2;
217597
+ if (step === 3 && (restoredDraft || !notes.length && !approval)) step = restoredDraft ? 2 : 1;
217072
217598
  }
217073
217599
  } catch {
217074
217600
  storageOk = false;
217075
217601
  }
217076
- const persist = () => {
217602
+ note.value = restoredDraft;
217603
+ function persist() {
217077
217604
  try {
217078
- localStorage.setItem(key, JSON.stringify({ notes, choice, approval, learningChoices, draft: $("note").value, mark, endMs, segmentId }));
217605
+ localStorage.setItem(key, JSON.stringify({ notes, choice, approval, learningChoices, draft: note.value, mark, endMs, segmentId, step }));
217079
217606
  } catch {
217080
217607
  storageOk = false;
217081
217608
  }
217082
- $("saved").textContent = storageOk ? "Guardado en este navegador" : "Descarga tus cambios antes de cerrar";
217083
- };
217084
- $("title").textContent = data.title;
217085
- $("version").textContent = data.version;
217086
- $("phase").textContent = data.stage === "directions" ? "01 \xB7 ELIGE UNA DIRECCI\xD3N" : data.stage === "delivery" ? "03 \xB7 TU ENTREGA" : "02 \xB7 REVISA TU VIDEO";
217087
- $("media-quality").textContent = data.video?.purpose === "preview" ? `Vista previa${data.video.quality ? " \xB7 " + data.video.quality + "p" : ""} \xB7 Revisa cortes, textos y audio` : data.video?.purpose === "final" ? "Render final" : "Vista de revisi\xF3n";
217088
- const player = $("player");
217089
- let mediaReady = false;
217609
+ $("saved").textContent = storageOk ? "Guardado en este navegador \xB7 Nada se env\xEDa solo" : "No se pudo guardar aqu\xED \xB7 Descarga tus cambios antes de cerrar";
217610
+ }
217090
217611
  function seek(ms) {
217091
217612
  if (mediaReady) {
217092
217613
  player.pause();
217093
217614
  player.currentTime = Math.min(Math.max(0, ms / 1e3), player.duration);
217094
217615
  }
217095
217616
  }
217096
- const feedback2 = () => ({ schemaVersion: 1, kind: "editorbrain.review-feedback", projectId: data.projectId, artifactId: data.artifactId, version: data.version, videoSha256: data.video?.sha256 ?? null, stage: data.stage, contextVersion: data.contextVersion ?? null, scope: "project", directionId: choice || null, decision: approval ? data.stage === "delivery" ? "approve_final" : "approve_sample" : "changes", comments: notes, ...approval ? { learningRequests: (data.learnings ?? []).filter((p) => learningChoices[p.id]?.selected).map((p) => ({ ...p, target: learningChoices[p.id].target, context: data.learningContext, userConfirmed: true })) } : {} });
217097
- const prompt = () => `Contin\xFAa mi proyecto ${data.projectId} desde la versi\xF3n ${data.version}. Adjunto mis decisiones del artefacto EditorBrain. Verifica artifactId y el hash del video antes de aplicarlas. Los cambios son solo de este video; conserva mi marca y lo dem\xE1s. Para una frase recortada, usa su segmentId en la transcripci\xF3n del artefacto y sus tiempos de origen, nunca como tiempos del montaje. ${data.video?.purpose === "preview" ? "Esta aprobaci\xF3n corresponde al borrador. Genera la entrega desde los originales con el perfil final del proyecto; nunca escales el archivo de la vista previa. " : ""}No gastes fuera del presupuesto ya autorizado. Entrega la nueva versi\xF3n con su artefacto actualizado. Solo si learningRequests contiene selecciones, guarda esas preferencias en el alcance elegido con la API de memoria y revisiones vigentes; no actives otras sugerencias. La aprobaci\xF3n del video no es consentimiento para compartir se\xF1ales de producto. Confirma lo que efectivamente se guard\xF3, no solo lo preparado aqu\xED.
217617
+ const feedback2 = () => ({ schemaVersion: 1, kind: "editorbrain.review-feedback", projectId: data.projectId, artifactId: data.artifactId, version: data.version, videoSha256: data.video?.sha256 ?? null, stage: data.stage, contextVersion: data.contextVersion ?? null, scope: "project", directionId: choice || null, decision: approvalReady() ? data.stage === "delivery" ? "approve_final" : "approve_sample" : "changes", comments: notes, ...approvalReady() ? { learningRequests: (data.learnings ?? []).filter((p) => learningChoices[p.id]?.selected).map((p) => ({ ...p, target: learningChoices[p.id].target, context: data.learningContext, userConfirmed: true })) } : {} });
217618
+ const draftWarning = () => note.value.trim() ? "Hay un comentario sin guardar. No interpretes este mensaje como una aprobaci\xF3n ni como la lista completa de cambios. P\xEDdeme guardar el comentario y volver a copiar la indicaci\xF3n.\n\n" : "";
217619
+ const prompt = () => `${draftWarning()}Contin\xFAa mi proyecto ${data.projectId} desde la versi\xF3n ${data.version}. Adjunto mis decisiones del artefacto EditorBrain. Verifica artifactId y el hash del video antes de aplicarlas. Los cambios son solo de este video; conserva mi marca y lo dem\xE1s. Para una frase recortada, usa su segmentId en la transcripci\xF3n del artefacto y sus tiempos de origen, nunca como tiempos del montaje. ${data.video?.purpose === "preview" ? "Esta revisi\xF3n corresponde al borrador. Si la decisi\xF3n es aprobar, genera la entrega desde los originales con el perfil final del proyecto; nunca escales el archivo de la vista previa. " : ""}No gastes fuera del presupuesto ya autorizado. Entrega la nueva versi\xF3n con su artefacto actualizado. Solo si learningRequests contiene selecciones, guarda esas preferencias en el alcance elegido con la API de memoria y revisiones vigentes; no actives otras sugerencias. La aprobaci\xF3n del video no es consentimiento para compartir se\xF1ales de producto. Confirma lo que efectivamente se guard\xF3, no solo lo preparado aqu\xED.
217098
217620
 
217099
217621
  ${JSON.stringify(feedback2(), null, 2)}`;
217100
217622
  const phonePrompt = () => `Quiero revisar en mi tel\xE9fono esta versi\xF3n de EditorBrain: proyecto ${data.projectId}, versi\xF3n ${data.version}, artifactId ${data.artifactId}, video SHA-256 ${data.video?.sha256 ?? "sin video"}. Mant\xE9n \xABEn computadora\xBB como opci\xF3n principal. ${data.stage === "directions" ? "Mu\xE9strame estas propuestas con im\xE1genes ligeras en el chat m\xF3vil; todav\xEDa no hay una muestra de video para registrar." : "Autorizo subir solo una copia ligera de esta muestra a mi proyecto privado de EditorBrain. Reutiliza la copia y el registro si ya existen; verifica el hash, el contexto, el espacio disponible y las reservas antes de subir. Conserva originales y master en mi computadora. No subas originales para completar una transcripci\xF3n. Si falta espacio, conserva la revisi\xF3n local y ofrece alternativas sin borrar archivos ni cambiar mi plan. Devu\xE9lveme el enlace autenticado al proyecto, nunca localhost ni un enlace p\xFAblico. Comprueba reproducci\xF3n y versi\xF3n. No crees un enlace hasta confirmar la subida y el registro."} Esto no aprueba la edici\xF3n ni autoriza generar contenido de pago. Mis comentarios locales no se sincronizan solos; te adjunto los guardados para que los concilies antes de continuar.
217101
217623
 
217102
217624
  ${JSON.stringify({ ...feedback2(), kind: "editorbrain.review-access-request", decision: "request_phone_review" }, null, 2)}`;
217103
- $("phone-copy").onclick = async () => {
217104
- if (note.value.trim()) {
217105
- status("Guarda tu comentario antes de preparar la revisi\xF3n en tel\xE9fono.");
217106
- return;
217625
+ function renderSteps() {
217626
+ if (isDirections) return;
217627
+ if (step === 3) player.pause();
217628
+ $("editing").hidden = step === 3;
217629
+ $("change-panel").hidden = step !== 2;
217630
+ $("watch-actions").hidden = step !== 1;
217631
+ $("change-actions").hidden = step !== 2;
217632
+ $("comments").hidden = step === 1;
217633
+ $("send-summary").hidden = step !== 3;
217634
+ $("handoff").hidden = step !== 3;
217635
+ $("learning-section").hidden = step !== 3 || !approvalReady() || !data.learnings?.length;
217636
+ const names = ["step-watch", "step-change", "step-send"];
217637
+ for (let index = 0; index < names.length; index++) {
217638
+ if (step === index + 1) $(names[index]).setAttribute("aria-current", "step");
217639
+ else $(names[index]).removeAttribute("aria-current");
217640
+ }
217641
+ $("step-title").textContent = step === 1 ? isDelivery ? "Tu video est\xE1 listo para revisar" : "Mira esta versi\xF3n" : step === 2 ? "Dinos qu\xE9 quieres cambiar" : "Todo listo para tu agente";
217642
+ $("intro").textContent = step === 1 ? "Reproduce el video. Puedes pedir ajustes o preparar tu aprobaci\xF3n." : step === 2 ? "Marca un momento o comenta sobre todo el video. Lo dem\xE1s se conserva." : "Revisa tu decisi\xF3n y ll\xE9vala a la misma conversaci\xF3n.";
217643
+ }
217644
+ function setStep(next, focus = true) {
217645
+ if (next === 3) {
217646
+ if (note.value.trim()) {
217647
+ status("Guarda tu comentario antes de preparar el env\xEDo.");
217648
+ note.focus();
217649
+ return;
217650
+ }
217651
+ if (!notes.length && !(approval && mediaReady)) {
217652
+ status("A\xF1ade un comentario o prepara tu aprobaci\xF3n antes de continuar.");
217653
+ return;
217654
+ }
217107
217655
  }
217108
- $("phone-request").value = phonePrompt();
217109
- try {
217110
- await navigator.clipboard.writeText(phonePrompt());
217111
- $("phone-status").textContent = "Copiado. P\xE9galo en el mismo chat; tu agente preparar\xE1 el acceso. Todav\xEDa no se ha subido nada.";
217112
- } catch {
217113
- $("phone-manual").open = true;
217114
- $("phone-request").focus();
217115
- $("phone-request").select();
217116
- $("phone-status").textContent = "Copia esta indicaci\xF3n y p\xE9gala en el mismo chat. Todav\xEDa no se ha subido nada.";
217656
+ step = next;
217657
+ renderSteps();
217658
+ persist();
217659
+ if (focus) {
217660
+ $("step-title").focus({ preventScroll: true });
217661
+ $("step-title").scrollIntoView({ block: "nearest" });
217117
217662
  }
217118
- };
217663
+ }
217664
+ function prepareComment() {
217665
+ if (!isDirections) setStep(2, false);
217666
+ note.focus({ preventScroll: true });
217667
+ note.scrollIntoView({ block: "nearest" });
217668
+ }
217669
+ function renderTarget() {
217670
+ $("target").textContent = mark !== void 0 ? `Momento ${time3(mark)}` : segmentId ? "Frase del original" : "Todo el video";
217671
+ $("mark").setAttribute("aria-pressed", String(mark !== void 0));
217672
+ $("scope-all").setAttribute("aria-pressed", String(mark === void 0 && !segmentId));
217673
+ $("clear-time").hidden = mark === void 0 && !segmentId;
217674
+ }
217675
+ function updateActions() {
217676
+ const pendingDraft = !!note.value.trim();
217677
+ const canExport = !pendingDraft && (isDirections ? !!choice : !!notes.length || approvalReady());
217678
+ $("approve").disabled = !!notes.length || !mediaReady;
217679
+ $("approve").textContent = approvalReady() ? "Aprobaci\xF3n preparada" : isDelivery ? "Aprobar esta entrega" : "Me gusta esta versi\xF3n";
217680
+ $("copy").textContent = pendingDraft ? "Guarda tu comentario primero" : copied ? "Copiado \xB7 P\xE9galo en el chat" : isDirections ? "Copiar mi elecci\xF3n" : approvalReady() ? "Copiar aprobaci\xF3n" : "Copiar cambios";
217681
+ $("copy").disabled = !canExport;
217682
+ $("download").disabled = !canExport;
217683
+ $("review-send").disabled = !notes.length || pendingDraft;
217684
+ $("step-send").disabled = !canExport || pendingDraft;
217685
+ $("draft-count").textContent = `${note.value.length} / 1500`;
217686
+ }
217687
+ function renderSummary() {
217688
+ const chosen = data.directions?.find((d) => d.id === choice);
217689
+ const pendingDraft = !!note.value.trim();
217690
+ $("summary-title").textContent = pendingDraft ? "Comentario sin guardar" : isDirections ? "Tu elecci\xF3n" : approvalReady() ? "Aprobaci\xF3n preparada" : `${notes.length} ${notes.length === 1 ? "cambio para tu agente" : "cambios para tu agente"}`;
217691
+ $("summary-detail").textContent = pendingDraft ? "Guarda tu comentario para preparar una indicaci\xF3n completa. Todav\xEDa no hay una aprobaci\xF3n lista para enviar." : isDirections ? chosen?.title || "" : `${data.version} \xB7 ${approvalReady() ? "Se enviar\xE1 \xFAnicamente la aprobaci\xF3n de esta versi\xF3n." : "Tu agente aplicar\xE1 estos ajustes. Esta vista todav\xEDa muestra la versi\xF3n anterior."}`;
217692
+ }
217693
+ function refreshOutput() {
217694
+ $("request").value = prompt();
217695
+ $("phone-request").value = draftWarning() + phonePrompt();
217696
+ }
217697
+ function draftChanged() {
217698
+ copied = false;
217699
+ updateActions();
217700
+ renderSummary();
217701
+ refreshOutput();
217702
+ persist();
217703
+ }
217119
217704
  function update() {
217120
- $("learning-section").hidden = !approval || !data.learnings?.length;
217121
217705
  $("notes").replaceChildren();
217122
217706
  $("markers").replaceChildren();
217123
- for (const n of notes) {
217124
- const card = text15("article", "");
217125
- const head = text15("div", "", "note-head");
217126
- const jump = button(n.startMs === void 0 ? "Todo el video" : time3(n.startMs), () => {
217127
- if (n.startMs !== void 0) seek(n.startMs);
217707
+ for (const item of notes) {
217708
+ const card = text15("article", ""), head = text15("div", "", "note-head");
217709
+ const jump = button(item.startMs === void 0 ? item.segmentId ? "Frase del original" : "Todo el video" : time3(item.startMs), () => {
217710
+ if (item.startMs !== void 0) {
217711
+ setStep(2, false);
217712
+ seek(item.startMs);
217713
+ player.scrollIntoView({ block: "nearest" });
217714
+ }
217128
217715
  });
217129
- jump.disabled = n.startMs === void 0;
217716
+ jump.disabled = item.startMs === void 0 || !mediaReady;
217130
217717
  head.append(jump, button("Quitar nota", () => {
217131
- removed = n;
217132
- notes = notes.filter((x) => x.id !== n.id);
217718
+ removed = item;
217719
+ notes = notes.filter((n) => n.id !== item.id);
217720
+ copied = false;
217133
217721
  update();
217134
217722
  $("undo").hidden = false;
217135
217723
  }));
217136
- card.append(head, text15("p", n.text));
217724
+ card.append(head, text15("p", item.text));
217137
217725
  $("notes").append(card);
217138
- if (n.startMs !== void 0) {
217139
- const marker = button(time3(n.startMs), () => seek(n.startMs));
217140
- marker.title = n.text;
217726
+ if (item.startMs !== void 0) {
217727
+ const marker = button(time3(item.startMs), () => seek(item.startMs));
217728
+ marker.title = item.text;
217729
+ marker.disabled = !mediaReady;
217141
217730
  $("markers").append(marker);
217142
217731
  }
217143
217732
  }
217733
+ $("notes-empty").hidden = !!notes.length;
217734
+ $("comments-label").textContent = `Mis comentarios${notes.length ? ` \xB7 ${notes.length}` : ""}`;
217144
217735
  $("pending").hidden = !notes.length;
217145
217736
  $("pending").textContent = `${notes.length} ${notes.length === 1 ? "cambio pendiente" : "cambios pendientes"}. El video todav\xEDa no incluye estas correcciones.`;
217146
- $("approve").disabled = !!notes.length || !mediaReady;
217147
- $("approve").textContent = approval ? "Aprobaci\xF3n preparada" : data.stage === "delivery" ? "Aprobar esta entrega" : "Me gusta esta versi\xF3n";
217148
- $("copy").textContent = data.stage === "directions" ? "Copiar mi elecci\xF3n" : approval ? "Copiar aprobaci\xF3n" : "Copiar cambios";
217149
- $("copy").disabled = data.stage === "directions" ? !choice : !notes.length && !approval;
217150
- $("download").disabled = $("copy").disabled;
217737
+ renderSummary();
217738
+ $("paste-step").classList.toggle("copied", copied);
217151
217739
  for (const card of Array.from(document.querySelectorAll("[data-choice]"))) {
217152
217740
  const selected = card.dataset.choice === choice;
217153
217741
  card.classList.toggle("chosen", selected);
217154
- card.querySelector("button")?.setAttribute("aria-pressed", String(selected));
217155
- }
217156
- $("request").value = prompt();
217157
- $("phone-request").value = phonePrompt();
217742
+ const pick3 = card.querySelector(".direction-choice");
217743
+ pick3.setAttribute("aria-pressed", String(selected));
217744
+ pick3.textContent = selected ? "Elegida para este video" : "Elegir " + card.querySelector("h3").textContent;
217745
+ card.querySelector(".chosen-label").hidden = !selected;
217746
+ }
217747
+ if (isDirections) {
217748
+ $("handoff").hidden = !choice;
217749
+ $("send-summary").hidden = !choice;
217750
+ } else renderSteps();
217751
+ updateActions();
217752
+ renderTarget();
217753
+ refreshOutput();
217158
217754
  persist();
217159
217755
  }
217160
- for (const proposal of data.learnings ?? []) {
217161
- const item = text15("article", ""), label = text15("label", ""), check2 = document.createElement("input");
217162
- check2.type = "checkbox";
217163
- check2.checked = learningChoices[proposal.id]?.selected ?? false;
217164
- const select = document.createElement("select");
217165
- select.setAttribute("aria-label", "Alcance: " + proposal.text);
217166
- const targets = [["project", "Solo este video"], ["style", "Este estilo, dentro de mi marca"], ["series", "Esta serie"], ["format", "Este formato"], ["brand", "Toda mi marca"]];
217167
- for (const [value, title] of targets) {
217168
- if (value === "series" && !data.learningContext?.seriesId || value === "format" && !data.learningContext?.formatId) continue;
217169
- const option = document.createElement("option");
217170
- option.value = value;
217171
- option.textContent = title;
217172
- select.append(option);
217173
- }
217174
- select.value = learningChoices[proposal.id]?.target ?? "project";
217175
- if (!select.value) select.value = "project";
217176
- const save = () => {
217177
- learningChoices[proposal.id] = { selected: check2.checked, target: select.value };
217178
- update();
217179
- };
217180
- check2.onchange = save;
217181
- select.onchange = save;
217182
- label.append(check2, document.createTextNode(" " + proposal.text));
217183
- item.append(label, text15("p", proposal.conditions || "Revisar seg\xFAn la escena.", "muted"), text15("p", "De tu correcci\xF3n: " + proposal.origin.evidence, "muted"), select);
217184
- $("learning-options").append(item);
217185
- }
217756
+ $("title").textContent = data.title;
217757
+ $("version").textContent = data.version;
217758
+ $("phase").textContent = isDirections ? "Propuestas para este video" : isDelivery ? "Entrega" : "Revisi\xF3n";
217759
+ $(isDirections ? "phase-directions" : isDelivery ? "phase-delivery" : "phase-review").setAttribute("aria-current", "step");
217760
+ $("media-quality").textContent = data.video?.purpose === "preview" ? `Vista previa${data.video.quality ? " \xB7 " + data.video.quality + "p" : ""} \xB7 Revisa cortes, textos y audio` : data.video?.purpose === "final" ? "Render final" : "Vista de revisi\xF3n";
217761
+ $("step-watch").onclick = () => setStep(1);
217762
+ $("step-change").onclick = () => setStep(2);
217763
+ $("step-send").onclick = () => setStep(3);
217764
+ $("start-changes").onclick = () => {
217765
+ setStep(2);
217766
+ note.focus({ preventScroll: true });
217767
+ };
217768
+ $("review-send").onclick = () => setStep(3);
217769
+ $("back-watch").onclick = () => setStep(1);
217770
+ $("back-edit").onclick = () => setStep(2);
217186
217771
  $("undo").onclick = () => {
217187
- if (removed) {
217188
- notes.push(removed);
217189
- removed = void 0;
217190
- update();
217191
- $("undo").hidden = true;
217772
+ if (!removed) return;
217773
+ if (notes.length >= 100) {
217774
+ status("Guarda esta tanda de cambios antes de recuperar m\xE1s notas.");
217775
+ return;
217192
217776
  }
217777
+ notes.push(removed);
217778
+ removed = void 0;
217779
+ approval = false;
217780
+ copied = false;
217781
+ update();
217782
+ $("undo").hidden = true;
217193
217783
  };
217194
- const note = $("note");
217195
- note.value = restoredDraft;
217196
- if (mark !== void 0) $("target").textContent = `Momento ${time3(mark)}`;
217197
- note.oninput = persist;
217198
- const clearTarget = () => {
217784
+ note.oninput = draftChanged;
217785
+ function clearTarget() {
217199
217786
  mark = void 0;
217200
217787
  endMs = void 0;
217201
217788
  segmentId = void 0;
217202
- $("target").textContent = "Todo el video";
217789
+ renderTarget();
217203
217790
  persist();
217204
- };
217791
+ }
217205
217792
  $("clear-time").onclick = clearTarget;
217793
+ $("scope-all").onclick = clearTarget;
217206
217794
  $("mark").onclick = () => {
217207
217795
  if (!mediaReady) return;
217208
217796
  player.pause();
217209
217797
  mark = Math.round(player.currentTime * 1e3);
217210
217798
  endMs = void 0;
217211
217799
  segmentId = void 0;
217212
- $("target").textContent = `Momento ${time3(mark)}`;
217800
+ renderTarget();
217213
217801
  persist();
217214
- note.focus();
217802
+ prepareComment();
217215
217803
  };
217216
217804
  $("back").onclick = () => seek(player.currentTime * 1e3 - 5e3);
217217
217805
  $("forward").onclick = () => seek(player.currentTime * 1e3 + 5e3);
217218
- $("form").onsubmit = (e) => {
217219
- e.preventDefault();
217806
+ $("form").onsubmit = (event) => {
217807
+ event.preventDefault();
217220
217808
  if (!note.value.trim()) return;
217809
+ if (note.value.length > 1500) {
217810
+ status("Acorta el comentario a 1500 caracteres.");
217811
+ return;
217812
+ }
217221
217813
  if (notes.length >= 100) {
217222
217814
  status("Guarda esta tanda de cambios antes de a\xF1adir m\xE1s.");
217223
217815
  return;
@@ -217230,26 +217822,36 @@ ${JSON.stringify({ ...feedback2(), kind: "editorbrain.review-access-request", de
217230
217822
  note.value = "";
217231
217823
  clearTarget();
217232
217824
  approval = false;
217825
+ copied = false;
217233
217826
  update();
217234
- status("Comentario guardado aqu\xED. Copia los cambios y p\xE9galos en tu chat para continuar.");
217827
+ $("comments").open = true;
217828
+ status(storageOk ? "Comentario guardado aqu\xED. Puedes a\xF1adir otro o preparar el env\xEDo." : "Comentario preparado. Este navegador no puede guardarlo: desc\xE1rgalo antes de cerrar.");
217235
217829
  };
217236
217830
  $("approve").onclick = () => {
217237
217831
  if (!mediaReady || notes.length) return;
217238
217832
  if (note.value.trim()) {
217239
217833
  status("Guarda o borra el comentario que est\xE1s escribiendo antes de aprobar.");
217834
+ prepareComment();
217240
217835
  return;
217241
217836
  }
217242
217837
  approval = true;
217838
+ copied = false;
217839
+ step = 3;
217243
217840
  update();
217841
+ $("step-title").focus({ preventScroll: true });
217244
217842
  status("Aprobaci\xF3n preparada. C\xF3piala al chat para que tu agente contin\xFAe.");
217245
217843
  };
217246
217844
  $("copy").onclick = async () => {
217247
217845
  if (note.value.trim()) {
217248
217846
  status("Guarda tu comentario antes de copiar los cambios.");
217847
+ prepareComment();
217249
217848
  return;
217250
217849
  }
217850
+ if (isDirections ? !choice : !notes.length && !(approval && mediaReady)) return;
217251
217851
  try {
217252
217852
  await navigator.clipboard.writeText(prompt());
217853
+ copied = true;
217854
+ updateActions();
217253
217855
  status("Copiado. P\xE9galo en el mismo chat de Claude o Codex para continuar.");
217254
217856
  } catch {
217255
217857
  $("manual").open = true;
@@ -217261,105 +217863,199 @@ ${JSON.stringify({ ...feedback2(), kind: "editorbrain.review-access-request", de
217261
217863
  $("download").onclick = () => {
217262
217864
  if (note.value.trim()) {
217263
217865
  status("Guarda tu comentario antes de descargar.");
217866
+ prepareComment();
217264
217867
  return;
217265
217868
  }
217869
+ if (isDirections ? !choice : !notes.length && !(approval && mediaReady)) return;
217266
217870
  const blob = new Blob([JSON.stringify(feedback2(), null, 2)], { type: "application/json" });
217267
- const url3 = URL.createObjectURL(blob), a = document.createElement("a");
217268
- a.href = url3;
217269
- a.download = `${data.projectId}-review-${data.artifactId.slice(0, 8)}.json`;
217270
- a.click();
217871
+ const url3 = URL.createObjectURL(blob), anchor2 = document.createElement("a");
217872
+ anchor2.href = url3;
217873
+ anchor2.download = `${data.projectId}-review-${data.artifactId.slice(0, 8)}.json`;
217874
+ anchor2.click();
217271
217875
  setTimeout(() => URL.revokeObjectURL(url3), 1e3);
217272
217876
  status("Adjunta el archivo descargado al mismo chat. Todav\xEDa no se ha enviado al agente.");
217273
217877
  };
217274
- if (data.stage === "directions") {
217275
- $("phone").querySelector("p").textContent = "Pide ver estas propuestas con im\xE1genes ligeras en tu chat m\xF3vil. No se sube ning\xFAn video autom\xE1ticamente.";
217878
+ $("phone-copy").onclick = async () => {
217879
+ if (note.value.trim()) {
217880
+ status("Guarda tu comentario antes de preparar la revisi\xF3n en tel\xE9fono.");
217881
+ prepareComment();
217882
+ return;
217883
+ }
217884
+ $("phone-request").value = phonePrompt();
217885
+ try {
217886
+ await navigator.clipboard.writeText(phonePrompt());
217887
+ $("phone-status").textContent = "Copiado. P\xE9galo en el mismo chat; tu agente preparar\xE1 el acceso. Todav\xEDa no se ha subido nada.";
217888
+ } catch {
217889
+ $("phone-manual").open = true;
217890
+ $("phone-request").focus();
217891
+ $("phone-request").select();
217892
+ $("phone-status").textContent = "Copia esta indicaci\xF3n y p\xE9gala en el mismo chat. Todav\xEDa no se ha subido nada.";
217893
+ }
217894
+ };
217895
+ const templateGroups = [
217896
+ { title: "Texto e imagen", items: [["Texto m\xE1s claro", "Haz este texto m\xE1s grande y f\xE1cil de leer."], ["Deja ver mi cara", "Mueve este elemento para que no tape mi cara."], ["Cambia la imagen", "Busca otra imagen para explicar mejor esta idea."]] },
217897
+ { title: "Audio y ritmo", items: [["Baja la m\xFAsica", "Baja la m\xFAsica para que se entienda mejor la voz."], ["Deja respirar", "Dale un poco m\xE1s de tiempo a este momento."], ["Hazlo m\xE1s \xE1gil", "Acorta este tramo manteniendo la idea completa."]] }
217898
+ ];
217899
+ for (const group of templateGroups) {
217900
+ const block = text15("section", "");
217901
+ block.append(text15("h4", group.title));
217902
+ for (const [title, suggestion] of group.items) block.append(button(title, () => {
217903
+ const next = note.value.trim() ? note.value + "\n" + suggestion : suggestion;
217904
+ if (next.length > 1500) {
217905
+ status("Tu comentario ya es largo. Ac\xF3rtalo antes de a\xF1adir esta idea.");
217906
+ return;
217907
+ }
217908
+ note.value = next;
217909
+ draftChanged();
217910
+ prepareComment();
217911
+ }));
217912
+ $("template-groups").append(block);
217913
+ }
217914
+ for (const proposal of data.learnings ?? []) {
217915
+ const item = text15("article", ""), label = text15("label", ""), check2 = document.createElement("input");
217916
+ check2.type = "checkbox";
217917
+ check2.checked = learningChoices[proposal.id]?.selected ?? false;
217918
+ const select = document.createElement("select");
217919
+ select.setAttribute("aria-label", "Alcance: " + proposal.text);
217920
+ for (const [value, title] of [["project", "Solo este video"], ["style", "Este estilo, dentro de mi marca"], ["series", "Esta serie"], ["format", "Este formato"], ["brand", "Toda mi marca"]]) {
217921
+ if (value === "series" && !data.learningContext?.seriesId || value === "format" && !data.learningContext?.formatId) continue;
217922
+ const option = document.createElement("option");
217923
+ option.value = value;
217924
+ option.textContent = title;
217925
+ select.append(option);
217926
+ }
217927
+ select.value = learningChoices[proposal.id]?.target ?? "project";
217928
+ if (!select.value) select.value = "project";
217929
+ learningChoices[proposal.id] = { selected: check2.checked, target: select.value };
217930
+ const save = () => {
217931
+ learningChoices[proposal.id] = { selected: check2.checked, target: select.value };
217932
+ copied = false;
217933
+ update();
217934
+ };
217935
+ check2.onchange = save;
217936
+ select.onchange = save;
217937
+ label.append(check2, document.createTextNode(proposal.text));
217938
+ item.append(label, text15("p", proposal.conditions || "Revisar seg\xFAn la escena.", "muted"), text15("p", "De tu correcci\xF3n: " + proposal.origin.evidence, "muted"), select);
217939
+ $("learning-options").append(item);
217940
+ }
217941
+ if (isDirections) {
217942
+ $("wizard").hidden = true;
217276
217943
  $("editing").hidden = true;
217944
+ $("comments").hidden = true;
217277
217945
  $("direction-grid").hidden = false;
217278
- $("intro").textContent = "Elige la propuesta que m\xE1s te guste. Despu\xE9s copia tu elecci\xF3n al chat.";
217279
- for (const d of data.directions) {
217946
+ $("step-title").textContent = "Elige el estilo de tu video";
217947
+ $("intro").textContent = "Son propuestas para este video. Elige la que m\xE1s te guste; tu agente preparar\xE1 la primera muestra con ella.";
217948
+ $("phone").querySelector("p").textContent = "Pide ver estas propuestas con im\xE1genes ligeras en tu chat m\xF3vil. No se sube ning\xFAn video autom\xE1ticamente.";
217949
+ $("back-edit").hidden = true;
217950
+ for (const direction of data.directions) {
217280
217951
  const card = text15("article", "", "direction");
217281
- card.dataset.choice = d.id;
217282
- if (d.preview) {
217283
- const m = document.createElement(d.preview.mimeType.startsWith("video/") ? "video" : "img");
217284
- m.src = d.preview.uri;
217285
- if (d.preview.mimeType.startsWith("video/")) {
217286
- m.controls = true;
217287
- m.playsInline = true;
217288
- m.preload = "metadata";
217289
- } else m.alt = d.title;
217290
- card.append(m);
217291
- } else card.append(text15("div", "Sin muestra visual adjunta", "no-preview"));
217292
- card.append(text15("h2", d.title), text15("p", d.description), button("Elegir " + d.title, () => {
217293
- choice = d.id;
217294
- update();
217295
- status("Elecci\xF3n guardada aqu\xED. Copia tu elecci\xF3n y p\xE9gala en el chat.");
217296
- }));
217297
- if (d.references?.length) {
217952
+ card.dataset.choice = direction.id;
217953
+ const media3 = text15("div", "", "direction-media");
217954
+ if (direction.preview) {
217955
+ const isVideo = direction.preview.mimeType.startsWith("video/");
217956
+ const element = document.createElement(isVideo ? "video" : "img");
217957
+ element.src = direction.preview.uri;
217958
+ if (isVideo) {
217959
+ element.controls = true;
217960
+ element.playsInline = true;
217961
+ element.preload = "metadata";
217962
+ element.setAttribute("aria-label", direction.title);
217963
+ } else {
217964
+ element.alt = direction.title;
217965
+ element.loading = "lazy";
217966
+ }
217967
+ media3.append(element);
217968
+ } else {
217969
+ const blank = text15("div", "", "no-preview");
217970
+ blank.append(text15("span", "A"), text15("span", "Sin muestra visual adjunta"));
217971
+ media3.append(blank);
217972
+ }
217973
+ const chosen = text15("span", "\u2713 Elegida", "chosen-label");
217974
+ chosen.hidden = true;
217975
+ media3.append(chosen);
217976
+ card.append(media3, text15("h3", direction.title), text15("p", direction.description));
217977
+ if (direction.references?.length) {
217298
217978
  const refs = text15("details", "");
217299
217979
  refs.append(text15("summary", "Ver referencias"));
217300
- for (const r of d.references) {
217301
- const a = text15("a", r.label);
217302
- a.href = r.url;
217303
- a.target = "_blank";
217304
- a.rel = "noopener noreferrer";
217305
- refs.append(a);
217980
+ for (const reference of direction.references) {
217981
+ const anchor2 = text15("a", reference.label);
217982
+ anchor2.href = reference.url;
217983
+ anchor2.target = "_blank";
217984
+ anchor2.rel = "noopener noreferrer";
217985
+ refs.append(anchor2);
217306
217986
  }
217307
217987
  card.append(refs);
217308
217988
  }
217989
+ card.append(button("Elegir " + direction.title, () => {
217990
+ choice = direction.id;
217991
+ copied = false;
217992
+ update();
217993
+ status("Elecci\xF3n preparada. Copia tu elecci\xF3n y p\xE9gala en el chat.");
217994
+ }, "direction-choice"));
217309
217995
  $("direction-grid").append(card);
217310
217996
  }
217311
217997
  } else {
217312
- player.src = data.video.uri;
217313
217998
  player.onloadedmetadata = () => {
217314
217999
  mediaReady = Number.isFinite(player.duration) && player.duration > 0;
217315
218000
  $("mark").disabled = !mediaReady;
218001
+ $("back").disabled = !mediaReady;
218002
+ $("forward").disabled = !mediaReady;
218003
+ $("media-error").hidden = true;
217316
218004
  if (data.transcript && Math.abs(player.duration * 1e3 - data.transcript.durationMs) > 300) {
217317
218005
  $("transcript").hidden = true;
218006
+ $("transcript-panel").hidden = true;
218007
+ $("workspace").classList.add("no-transcript");
217318
218008
  status("La transcripci\xF3n no coincide con la duraci\xF3n de esta muestra. Pide corregir sus tiempos; puedes dejar comentarios sobre el video.");
217319
218009
  }
217320
218010
  update();
217321
218011
  };
217322
218012
  player.onerror = () => {
217323
218013
  mediaReady = false;
217324
- $("mark").disabled = true;
217325
- status(data.video.uri.startsWith("data:") ? "Este visor no pudo reproducir el video. Pide a tu agente abrir una revisi\xF3n local ligera. No apruebes una muestra que no pudiste revisar." : "No se pudo cargar el video. Pide a tu agente mantener abierto el servidor de revisi\xF3n y comprobar el preview en tu navegador. No apruebes una muestra que no pudiste revisar.");
218014
+ approval = false;
218015
+ copied = false;
218016
+ for (const id4 of ["mark", "back", "forward"]) $(id4).disabled = true;
218017
+ const message = data.video.uri.startsWith("data:") ? "Este visor no pudo reproducir el video. Pide a tu agente abrir una revisi\xF3n local ligera. No apruebes una muestra que no pudiste revisar." : "No se pudo cargar el video. Pide a tu agente mantener abierto el servidor de revisi\xF3n y comprobar el preview en tu navegador. No apruebes una muestra que no pudiste revisar.";
218018
+ $("media-error").textContent = message;
218019
+ $("media-error").hidden = false;
218020
+ status(message);
217326
218021
  update();
217327
218022
  };
217328
218023
  player.ontimeupdate = () => {
217329
218024
  $("clock").textContent = `${time3(player.currentTime * 1e3)} / ${time3(Number.isFinite(player.duration) ? player.duration * 1e3 : 0)}`;
217330
- for (const e of Array.from(document.querySelectorAll("[data-start]"))) e.classList.toggle("speaking", player.currentTime * 1e3 >= Number(e.dataset.start) && player.currentTime * 1e3 < Number(e.dataset.end));
218025
+ for (const row of Array.from(document.querySelectorAll("[data-start]"))) row.classList.toggle("speaking", player.currentTime * 1e3 >= Number(row.dataset.start) && player.currentTime * 1e3 < Number(row.dataset.end));
217331
218026
  };
217332
218027
  if (data.transcript?.segments.length) {
217333
218028
  $("transcript").hidden = false;
217334
- for (const s of data.transcript.segments) {
217335
- const row = text15("article", "", s.state === "removed" ? "removed" : "");
217336
- row.dataset.state = s.state;
217337
- if (s.state === "kept") {
217338
- row.dataset.start = s.startMs;
217339
- row.dataset.end = s.endMs;
217340
- row.append(button(time3(s.startMs) + " \xB7 " + s.text, () => seek(s.startMs)));
218029
+ $("transcript-panel").hidden = false;
218030
+ for (const segment of data.transcript.segments) {
218031
+ const row = text15("article", "", segment.state === "removed" ? "removed" : "");
218032
+ row.dataset.state = segment.state;
218033
+ if (segment.state === "kept") {
218034
+ row.dataset.start = segment.startMs;
218035
+ row.dataset.end = segment.endMs;
218036
+ row.append(button(time3(segment.startMs) + " \xB7 " + segment.text, () => seek(segment.startMs)));
217341
218037
  } else {
217342
218038
  row.hidden = true;
217343
- row.append(text15("small", "Recortada del original \xB7 " + time3(s.source.startMs)), text15("p", s.text));
218039
+ row.append(text15("small", "Recortada del original \xB7 " + time3(segment.source.startMs)), text15("p", segment.text));
217344
218040
  }
217345
- row.append(button(s.state === "kept" ? "Pedir quitar frase" : "Pedir recuperar frase", () => {
218041
+ row.append(button(segment.state === "kept" ? "Pedir quitar frase" : "Pedir recuperar frase", () => {
217346
218042
  if (note.value.trim() && !window.confirm("\xBFReemplazar tu comentario sin guardar?")) return;
217347
- segmentId = s.id;
217348
- mark = s.state === "kept" ? s.startMs : void 0;
217349
- endMs = s.state === "kept" ? s.endMs : void 0;
217350
- note.value = s.state === "kept" ? `Quita esta frase: \xAB${s.text}\xBB. Conserva lo dem\xE1s y revisa la uni\xF3n del audio.` : `Recupera esta frase: \xAB${s.text}\xBB. Busca su tramo original en la transcripci\xF3n y conserva lo dem\xE1s.`;
217351
- $("target").textContent = mark === void 0 ? "Frase del original" : `Momento ${time3(mark)}`;
217352
- persist();
217353
- note.focus();
218043
+ segmentId = segment.id;
218044
+ mark = segment.state === "kept" ? segment.startMs : void 0;
218045
+ endMs = segment.state === "kept" ? segment.endMs : void 0;
218046
+ note.value = segment.state === "kept" ? `Quita esta frase: \xAB${segment.text}\xBB. Conserva lo dem\xE1s y revisa la uni\xF3n del audio.` : `Recupera esta frase: \xAB${segment.text}\xBB. Busca su tramo original en la transcripci\xF3n y conserva lo dem\xE1s.`;
218047
+ draftChanged();
218048
+ renderTarget();
218049
+ prepareComment();
217354
218050
  }));
217355
218051
  $("phrases").append(row);
217356
218052
  }
217357
- const cuts = data.transcript.segments.some((s) => s.state === "removed");
217358
- $("show-cuts-label").hidden = !cuts;
217359
- $("show-cuts").onchange = (e) => {
217360
- for (const row of Array.from(document.querySelectorAll('[data-state="removed"]'))) row.hidden = !e.target.checked;
218053
+ $("show-cuts-label").hidden = !data.transcript.segments.some((segment) => segment.state === "removed");
218054
+ $("show-cuts").onchange = (event) => {
218055
+ for (const row of Array.from(document.querySelectorAll('[data-state="removed"]'))) row.hidden = !event.target.checked;
217361
218056
  };
217362
- }
218057
+ } else $("workspace").classList.add("no-transcript");
218058
+ player.src = data.video.uri;
217363
218059
  }
217364
218060
  $("future").onclick = () => {
217365
218061
  $("future-details").open = !$("future-details").open;
@@ -217367,116 +218063,198 @@ ${JSON.stringify({ ...feedback2(), kind: "editorbrain.review-access-request", de
217367
218063
  update();
217368
218064
  }
217369
218065
  function renderReviewArtifact(data, wordmark) {
217370
- const script = `(${reviewApp.toString()})();`, hash11 = createHash24("sha256").update(script).digest("base64");
218066
+ const script = `(${reviewApp.toString()})();`;
218067
+ const hash13 = createHash24("sha256").update(script).digest("base64");
217371
218068
  const json2 = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
217372
- 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-${hash11}'; 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>
217373
- *{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}
217374
- @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}}
217375
- @media(prefers-reduced-motion:no-preference){button,.direction{transition:background .15s,border-color .15s}}
217376
- </style></head><body><main><header><div aria-label="EditorBrain">${wordmark.replaceAll("#f3ede3", "#ffffff")}</div><span id="version"></span></header><p class="muted" id="review-location">En computadora \xB7 No ocupa almacenamiento en la nube</p><p class="eyebrow" id="phase"></p><h1 id="title"></h1><p class="intro" id="intro">Mira tu video y marca lo que quieras ajustar. Lo dem\xE1s se conserva.</p><div id="direction-grid" hidden></div><section id="editing"><p id="pending" role="status" hidden></p><div class="workspace"><div class="preview"><p id="media-quality" class="muted"></p><div class="screen"><video id="player" controls playsinline preload="metadata" aria-label="Tu edici\xF3n"></video></div><div class="controls"><button id="back" type="button">\u22125 s</button><span id="clock">00:00.0</span><button id="forward" type="button">+5 s</button></div><div id="markers" aria-label="Momentos comentados"></div></div><aside><h2>\xBFQu\xE9 cambiamos?</h2><p>Solo para este video. Tus preferencias de marca se conservan.</p><form id="form"><div class="target"><button id="mark" type="button" disabled>Marcar este momento</button><span id="target">Todo el video</span><button id="clear-time" type="button" aria-label="Quitar momento">\xD7</button></div><label for="note" class="muted">Tu comentario</label><textarea id="note" maxlength="1500" placeholder="Este texto m\xE1s grande\u2026 / Conserva esta explicaci\xF3n\u2026" required></textarea><button class="save primary" type="submit">Guardar comentario</button></form><details id="transcript" hidden><summary>Revisar cortes desde el texto</summary><p class="muted">Toca una frase para ubicarla. Quitar o recuperar prepara un comentario, no modifica este preview.</p><label id="show-cuts-label"><input id="show-cuts" type="checkbox"> Mostrar frases recortadas</label><div id="phrases"></div></details><button id="approve" type="button" disabled>Me gusta esta versi\xF3n</button><p class="muted">La aprobaci\xF3n tambi\xE9n se env\xEDa al chat en el siguiente paso.</p></aside></div><details id="comments"><summary>Mis comentarios</summary><div id="notes"></div><button id="undo" type="button" hidden>Deshacer eliminaci\xF3n de nota</button></details></section><section id="learning-section" hidden><details><summary>Guardar lo que me gust\xF3 \xB7 opcional</summary><p class="muted">Elige qu\xE9 recordar y d\xF3nde. Nada est\xE1 seleccionado. Se guardar\xE1 cuando pegues la solicitud en tu chat y el agente confirme el resultado.</p><div id="learning-options"></div></details></section><section class="handoff"><div class="handoff-head"><div><h2>Contin\xFAa en tu chat</h2><p>1. Copia tus cambios. &nbsp; 2. P\xE9galos en Claude o Codex.</p><p>Este artefacto no inicia al agente por s\xED solo.</p></div><div class="actions"><button id="copy" class="primary" type="button" disabled>Copiar cambios</button><button id="download" type="button" disabled>Descargar cambios</button></div></div><p id="status" role="status" aria-live="polite"></p><details id="manual"><summary>Ver indicaci\xF3n para copiar</summary><textarea id="request" readonly aria-label="Indicaci\xF3n para tu agente"></textarea></details></section><details id="phone"><summary>\xBFQuieres revisarlo en tu tel\xE9fono?</summary><p class="muted">P\xEDdeselo a tu agente desde el mismo chat. Solo se sube la muestra que quieras revisar; los originales se quedan en tu computadora.</p><button id="phone-copy" type="button">Copiar solicitud para mi agente</button><p id="phone-status" class="muted" role="status" aria-live="polite"></p><details id="phone-manual"><summary>Ver indicaci\xF3n para copiar</summary><textarea id="phone-request" readonly aria-label="Solicitud de revisi\xF3n en tel\xE9fono"></textarea></details></details><details id="future-details"><summary>\xBFY si quiero cambiar mi estilo para futuros videos?</summary><p class="future-note">P\xEDdeselo expl\xEDcitamente a tu agente o cambia \xABC\xF3mo editas\xBB en EditorBrain. Los comentarios son solo de este video. Para recordar una correcci\xF3n, elige su alcance en \xABGuardar lo que me gust\xF3\xBB y env\xEDala al chat. Nada actualiza tu marca autom\xE1ticamente.</p></details><footer><span id="saved"></span><span>EditorBrain \xB7 Revisi\xF3n privada \xB7 Sin env\xEDos autom\xE1ticos</span></footer><button id="future" hidden type="button"></button></main><script id="review-data" type="application/json">${json2}</script><script>${script}</script></body></html>`;
218069
+ return `<!doctype html>
218070
+ <html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
218071
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash13}'; 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'">
218072
+ <title>EditorBrain \xB7 Tu edici\xF3n</title><style>${reviewArtifactCss}</style></head>
218073
+ <body>
218074
+ <header class="topbar">
218075
+ <div class="brand" role="img" aria-label="EditorBrain">${wordmark.replaceAll("#f3ede3", "#29231F")}</div>
218076
+ <div class="project-heading"><h1 id="title"></h1><span id="version"></span></div>
218077
+ <div class="header-actions"><ol class="project-stages" aria-label="Etapa de este artefacto">
218078
+ <li id="phase-directions"><b>01</b> Propuestas</li><li id="phase-review"><b>02</b> Revisi\xF3n</li><li id="phase-delivery"><b>03</b> Entrega</li>
218079
+ </ol><button id="how-it-works" type="button" class="guide-button" aria-haspopup="dialog" aria-controls="review-guide"><span aria-hidden="true">?</span> C\xF3mo funciona</button></div>
218080
+ </header>
218081
+ <dialog id="review-guide" class="review-guide" aria-labelledby="guide-title" aria-describedby="guide-intro">
218082
+ <div class="guide-heading"><p class="eyebrow">Una gu\xEDa r\xE1pida</p><button id="guide-dismiss" type="button" aria-label="Cerrar gu\xEDa" autofocus>\xD7</button></div>
218083
+ <h2 id="guide-title"></h2><p id="guide-intro">Revisa aqu\xED. Contin\xFAa en tu chat.</p>
218084
+ <ol id="guide-steps" class="guide-steps"></ol><p id="guide-approval" class="guide-approval"></p>
218085
+ <div class="guide-storage"><strong>Se queda en tu navegador</strong><p>Tus borradores y decisiones se guardan aqu\xED, si el navegador lo permite. No se sincronizan entre dispositivos ni se env\xEDan al agente autom\xE1ticamente. Tu marca no cambia.</p><p>Si no se pudo guardar, copia o descarga antes de cerrar.</p></div>
218086
+ <button id="guide-close" type="button" class="primary">Entendido</button>
218087
+ </dialog>
218088
+ <noscript><p class="noscript">Para reproducir, comentar y preparar tu respuesta, abre este artefacto en un navegador con JavaScript. Nada se env\xEDa autom\xE1ticamente.</p></noscript>
218089
+ <main class="shell">
218090
+ <div class="utility"><p id="review-location"><span class="privacy-dot"></span>En computadora \xB7 Revisi\xF3n privada</p><p id="saved">Se guarda en este navegador \xB7 Nada se env\xEDa solo</p></div>
218091
+ <nav id="wizard" class="wizard" aria-label="Pasos de esta revisi\xF3n">
218092
+ <button id="step-watch" type="button" aria-current="step"><span>01</span> Mira</button>
218093
+ <button id="step-change" type="button"><span>02</span> Cambia</button>
218094
+ <button id="step-send" type="button" disabled><span>03</span> Env\xEDa</button>
218095
+ </nav>
218096
+ <div class="section-intro"><p id="phase" class="eyebrow"></p><h2 id="step-title" tabindex="-1">Mira tu video</h2><p id="intro"></p></div>
218097
+ <div id="direction-grid" hidden></div>
218098
+ <p id="media-error" class="notice error" role="alert" hidden></p>
218099
+ <section id="editing" class="step-content">
218100
+ <p id="pending" class="notice" role="status" hidden></p>
218101
+ <div id="workspace" class="workspace">
218102
+ <div class="preview">
218103
+ <div class="media-meta"><p id="media-quality" class="muted"></p></div>
218104
+ <div class="screen"><video id="player" controls playsinline preload="metadata" aria-label="Tu edici\xF3n"></video></div>
218105
+ <div class="controls"><span id="clock">00:00.0</span><div class="controls-actions"><button id="back" type="button" disabled aria-label="Retroceder 5 segundos">\u22125 s</button><button id="forward" type="button" disabled aria-label="Avanzar 5 segundos">+5 s</button></div></div>
218106
+ <div id="markers" aria-label="Momentos comentados"></div>
218107
+ <div id="watch-actions" class="watch-actions">
218108
+ <button id="start-changes" type="button" class="primary">Quiero hacer cambios</button>
218109
+ <button id="approve" type="button" disabled>Me gusta esta versi\xF3n</button>
218110
+ <p>Tu decisi\xF3n se prepara aqu\xED. T\xFA la copias al chat para continuar.</p>
218111
+ </div>
218112
+ <section id="change-panel" class="change-panel" hidden>
218113
+ <h3>\xBFQu\xE9 cambiamos?</h3><p class="muted">Solo para este video. Tus preferencias de marca se conservan.</p>
218114
+ <form id="form">
218115
+ <fieldset><legend>\xBFD\xF3nde est\xE1 el cambio?</legend><div class="target">
218116
+ <button id="mark" type="button" disabled aria-pressed="false">Marcar este momento</button>
218117
+ <button id="scope-all" type="button" aria-pressed="true">En todo el video</button>
218118
+ <span id="target">Todo el video</span><button id="clear-time" type="button" aria-label="Quitar momento" hidden>\xD7</button>
218119
+ </div></fieldset>
218120
+ <details id="moment-help" class="context-help"><summary>\xBFC\xF3mo elijo el momento?</summary><p>Coloca el video en el punto que quieres comentar y pulsa Marcar este momento. El video se pausa y ese segundo queda unido a tu nota. En todo el video quita la marca de tiempo; no cambia el texto que escribiste.</p></details>
218121
+ <label for="note">Tu comentario</label><textarea id="note" maxlength="1500" placeholder="Por ejemplo: baja la m\xFAsica aqu\xED para escuchar mejor mi voz\u2026" required></textarea>
218122
+ <details class="templates"><summary>Ideas para comentar</summary><div id="template-groups" class="template-groups"></div></details>
218123
+ <div class="form-footer"><span id="draft-count">0 / 1500</span><button class="save primary" type="submit">Guardar comentario</button></div>
218124
+ </form>
218125
+ </section>
218126
+ <div id="change-actions" class="change-actions" hidden><button id="back-watch" type="button" class="text-button">\u2190 Volver al video</button><button id="review-send" type="button" class="primary" disabled>Preparar env\xEDo \u2192</button></div>
218127
+ </div>
218128
+ <aside id="transcript-panel" class="transcript-panel" hidden>
218129
+ <details id="transcript" hidden><summary>Revisar cortes desde el texto</summary><p class="muted">Toca una frase para ubicarla. Quitar o recuperar prepara un comentario; no modifica este video.</p>
218130
+ <label id="show-cuts-label"><input id="show-cuts" type="checkbox"> Mostrar frases recortadas</label><div id="phrases"></div>
218131
+ </details>
218132
+ </aside>
218133
+ </div>
218134
+ </section>
218135
+ <section id="send-summary" class="send-summary step-content" hidden><span class="summary-symbol" aria-hidden="true">\u2197</span><div><h3 id="summary-title"></h3><p id="summary-detail"></p></div></section>
218136
+ <details id="comments" class="comments" hidden><summary id="comments-label">Mis comentarios</summary><p id="notes-empty">No has guardado comentarios.</p><div id="notes"></div><button id="undo" type="button" hidden>Deshacer eliminaci\xF3n de nota</button></details>
218137
+ <section id="learning-section" class="learning-section" hidden><details><summary>Guardar lo que me gust\xF3 \xB7 opcional</summary><p>Elige qu\xE9 recordar y d\xF3nde. Solo se recuerdan las opciones que marques. Se guardar\xE1 cuando pegues la solicitud en tu chat y el agente confirme el resultado.</p><div id="learning-options"></div></details></section>
218138
+ <section id="handoff" class="handoff" hidden>
218139
+ <h2>Contin\xFAa en tu chat</h2><p class="muted">Dos pasos. Tu agente recibe la versi\xF3n y los momentos exactos.</p>
218140
+ <ol class="handoff-steps">
218141
+ <li><span class="step-number">1</span><strong>Copia tu mensaje</strong><p>Incluye tu decisi\xF3n y los comentarios que guardaste.</p><button id="copy" class="primary" type="button" disabled>Copiar cambios</button></li>
218142
+ <li id="paste-step"><span class="step-number">2</span><strong>P\xE9galo en Claude o Codex</strong><p>En la misma conversaci\xF3n donde est\xE1s editando este video.</p><span class="chat-label">Este artefacto no inicia al agente por s\xED solo.</span></li>
218143
+ </ol>
218144
+ <div class="handoff-options"><button id="back-edit" class="text-button" type="button">\u2190 Revisar mis cambios</button><button id="download" class="text-button" type="button" disabled>Prefiero descargar un archivo</button>
218145
+ <details id="manual"><summary>Ver indicaci\xF3n para copiar</summary><textarea id="request" readonly aria-label="Indicaci\xF3n para tu agente"></textarea></details>
218146
+ </div>
218147
+ </section>
218148
+ <p id="status" role="status" aria-live="polite"></p>
218149
+ <div class="auxiliary">
218150
+ <details id="phone"><summary>\xBFQuieres revisarlo en tu tel\xE9fono?</summary><p class="muted">P\xEDdeselo a tu agente desde el mismo chat. Solo se sube la muestra que quieras revisar; los originales se quedan en tu computadora.</p><button id="phone-copy" type="button">Copiar solicitud para mi agente</button><p id="phone-status" class="muted" role="status" aria-live="polite"></p><details id="phone-manual"><summary>Ver indicaci\xF3n para copiar</summary><textarea id="phone-request" readonly aria-label="Solicitud de revisi\xF3n en tel\xE9fono"></textarea></details></details>
218151
+ <details id="future-details"><summary>\xBFY si quiero cambiar mi estilo para futuros videos?</summary><p class="future-note">P\xEDdeselo expl\xEDcitamente a tu agente o cambia \xABC\xF3mo editas\xBB en EditorBrain. Los comentarios son solo de este video. Para recordar una correcci\xF3n, elige su alcance en \xABGuardar lo que me gust\xF3\xBB y env\xEDala al chat. Nada actualiza tu marca autom\xE1ticamente.</p></details>
218152
+ </div>
218153
+ <footer><span>EditorBrain \xB7 Tu edici\xF3n, con criterio</span><span>Revisi\xF3n privada \xB7 Sin env\xEDos autom\xE1ticos</span></footer><button id="future" hidden type="button"></button>
218154
+ </main><script id="review-data" type="application/json">${json2}</script><script>${script}</script></body></html>`;
217377
218155
  }
217378
218156
 
217379
218157
  // packages/cli/src/review-artifact.ts
217380
- var invalid9 = (message) => {
218158
+ var invalid10 = (message) => {
217381
218159
  throw new CliError("INVALID_REVIEW_ARTIFACT", message, "See references/production-continuity.md. Use a new .editorbrain-local/.../review.html output for each version.");
217382
218160
  };
217383
218161
  var object19 = (v, keys4) => {
217384
- if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys4.includes(k))) invalid9("Unexpected artifact fields.");
218162
+ if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys4.includes(k))) invalid10("Unexpected artifact fields.");
217385
218163
  return v;
217386
218164
  };
217387
218165
  function text13(v, max) {
217388
- if (typeof v !== "string" || !v.trim() || v.length > max) invalid9("Missing or oversized artifact text.");
218166
+ if (typeof v !== "string" || !v.trim() || v.length > max) invalid10("Missing or oversized artifact text.");
217389
218167
  return v.trim();
217390
218168
  }
217391
218169
  function media2(v) {
217392
218170
  const m = object19(v, ["file", "sha256", "purpose", "quality"]);
217393
218171
  const file2 = text13(m.file, 4096);
217394
- if (/^[a-z]+:\/\//i.test(file2)) invalid9("Use a local media file, never a remote or signed URL.");
217395
- if (m.sha256 !== void 0 && (typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256))) invalid9("Invalid media hash.");
217396
- if (m.purpose !== void 0 && !["preview", "final"].includes(m.purpose)) invalid9("Media purpose must be preview or final.");
217397
- if (m.quality !== void 0 && (m.purpose !== "preview" || ![480, 720].includes(m.quality))) invalid9("Preview quality must be 480 or 720 with purpose preview.");
218172
+ if (/^[a-z]+:\/\//i.test(file2)) invalid10("Use a local media file, never a remote or signed URL.");
218173
+ if (m.sha256 !== void 0 && (typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256))) invalid10("Invalid media hash.");
218174
+ if (m.purpose !== void 0 && !["preview", "final"].includes(m.purpose)) invalid10("Media purpose must be preview or final.");
218175
+ if (m.quality !== void 0 && (m.purpose !== "preview" || ![480, 720].includes(m.quality))) invalid10("Preview quality must be 480 or 720 with purpose preview.");
217398
218176
  return { file: file2, ...m.sha256 ? { sha256: m.sha256 } : {}, ...m.purpose ? { purpose: m.purpose } : {}, ...m.quality ? { quality: m.quality } : {} };
217399
218177
  }
217400
218178
  function parseReviewArtifact(value) {
217401
218179
  const r = object19(value, ["schemaVersion", "projectId", "title", "version", "stage", "video", "transcript", "directions", "contextVersion", "learnings", "learningContext"]);
217402
- if (r.schemaVersion !== 1 || !["directions", "review", "delivery"].includes(r.stage)) invalid9("Use schemaVersion 1 and stage directions, review or delivery.");
218180
+ if (r.schemaVersion !== 1 || !["directions", "review", "delivery"].includes(r.stage)) invalid10("Use schemaVersion 1 and stage directions, review or delivery.");
217403
218181
  const projectId = text13(r.projectId, 80);
217404
218182
  assertIdentifier(projectId);
217405
218183
  const result2 = { schemaVersion: 1, projectId, title: text13(r.title, 120), version: text13(r.version, 80), stage: r.stage };
217406
218184
  if (r.contextVersion !== void 0) {
217407
- if (typeof r.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(r.contextVersion)) invalid9("Use the exact editorial context hash.");
218185
+ if (typeof r.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(r.contextVersion)) invalid10("Use the exact editorial context hash.");
217408
218186
  result2.contextVersion = r.contextVersion;
217409
218187
  }
217410
218188
  if (r.learnings !== void 0) {
217411
218189
  try {
217412
218190
  result2.learnings = parseReviewLearnings(r.learnings, projectId);
217413
218191
  } catch (e) {
217414
- invalid9(e.message);
218192
+ invalid10(e.message);
217415
218193
  }
217416
218194
  }
217417
218195
  if (r.learningContext !== void 0) {
217418
218196
  const c = object19(r.learningContext, ["brandId", "styleId", "formatId", "seriesId"]);
217419
218197
  assertIdentifier(text13(c.brandId, 80));
217420
218198
  assertIdentifier(text13(c.styleId, 80));
217421
- if (memoryContextIssues({ ...c.formatId !== void 0 ? { formatId: c.formatId } : {}, ...c.seriesId !== void 0 ? { seriesId: c.seriesId } : {} }).length) invalid9("Invalid learning format or series.");
218199
+ if (memoryContextIssues({ ...c.formatId !== void 0 ? { formatId: c.formatId } : {}, ...c.seriesId !== void 0 ? { seriesId: c.seriesId } : {} }).length) invalid10("Invalid learning format or series.");
217422
218200
  result2.learningContext = c;
217423
218201
  }
217424
- if (result2.learnings?.length && (!result2.learningContext || r.stage === "directions")) invalid9("Learning proposals need the selected context and a review/delivery.");
218202
+ if (result2.learnings?.length && (!result2.learningContext || r.stage === "directions")) invalid10("Learning proposals need the selected context and a review/delivery.");
217425
218203
  if (r.video !== void 0) result2.video = media2(r.video);
217426
- if (result2.stage === "delivery" && result2.video?.purpose === "preview") invalid9("A preview cannot be the final delivery. Render the approved edit from originals at the final output profile first.");
218204
+ if (result2.stage === "delivery" && result2.video?.purpose === "preview") invalid10("A preview cannot be the final delivery. Render the approved edit from originals at the final output profile first.");
217427
218205
  if (r.transcript !== void 0) {
217428
218206
  try {
217429
218207
  result2.transcript = parseReviewTranscript(r.transcript);
217430
218208
  } catch (e) {
217431
- invalid9(e.message);
218209
+ invalid10(e.message);
217432
218210
  }
217433
218211
  }
217434
218212
  if (r.directions !== void 0) {
217435
- if (!Array.isArray(r.directions) || r.directions.length < 1 || r.directions.length > 3) invalid9("Use one to three visual directions.");
218213
+ if (!Array.isArray(r.directions) || r.directions.length < 1 || r.directions.length > 3) invalid10("Use one to three visual directions.");
217436
218214
  const ids2 = /* @__PURE__ */ new Set();
217437
218215
  result2.directions = r.directions.map((v) => {
217438
218216
  const d = object19(v, ["id", "title", "description", "preview", "references"]), id4 = text13(d.id, 80);
217439
218217
  assertIdentifier(id4);
217440
- if (ids2.has(id4)) invalid9("Direction IDs must be unique.");
218218
+ if (ids2.has(id4)) invalid10("Direction IDs must be unique.");
217441
218219
  ids2.add(id4);
217442
218220
  let references;
217443
218221
  if (d.references !== void 0) {
217444
- if (!Array.isArray(d.references) || d.references.length > 5) invalid9("Use up to five inspected reference links per direction.");
218222
+ if (!Array.isArray(d.references) || d.references.length > 5) invalid10("Use up to five inspected reference links per direction.");
217445
218223
  references = d.references.map((v2) => {
217446
218224
  const ref = object19(v2, ["label", "url"]), label = text13(ref.label, 140), url3 = text13(ref.url, 2e3);
217447
218225
  let parsed;
217448
218226
  try {
217449
218227
  parsed = new URL(url3);
217450
218228
  } catch {
217451
- invalid9("Use an HTTPS reference link.");
218229
+ invalid10("Use an HTTPS reference link.");
217452
218230
  }
217453
- if (parsed.protocol !== "https:" || parsed.username || parsed.password) invalid9("Use an HTTPS reference link without credentials.");
218231
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) invalid10("Use an HTTPS reference link without credentials.");
217454
218232
  return { label, url: url3 };
217455
218233
  });
217456
218234
  }
217457
218235
  return { id: id4, title: text13(d.title, 100), description: text13(d.description, 500), ...d.preview ? { preview: media2(d.preview) } : {}, ...references ? { references } : {} };
217458
218236
  });
217459
218237
  }
217460
- if (result2.stage === "directions" && (!result2.directions?.length || result2.video || result2.transcript)) invalid9("Direction stage needs visual proposals, without an edited-video transcript.");
217461
- if (result2.stage !== "directions" && (!result2.video || result2.directions)) invalid9("Review/delivery needs one video; keep direction choices in the earlier artifact.");
218238
+ if (result2.stage === "directions" && (!result2.directions?.length || result2.video || result2.transcript)) invalid10("Direction stage needs visual proposals, without an edited-video transcript.");
218239
+ if (result2.stage !== "directions" && (!result2.video || result2.directions)) invalid10("Review/delivery needs one video; keep direction choices in the earlier artifact.");
217462
218240
  return result2;
217463
218241
  }
217464
218242
  async function prepareMedia(root, input2, kind2, mediaDir, entries) {
217465
- const path = resolve18(root, input2.file), extension = extname8(path).toLowerCase();
218243
+ const path = resolve18(root, input2.file), extension = extname9(path).toLowerCase();
217466
218244
  const mime2 = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
217467
- if (!mime2[extension] || kind2 === "video" && !mime2[extension].startsWith("video/")) invalid9("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
218245
+ if (!mime2[extension] || kind2 === "video" && !mime2[extension].startsWith("video/")) invalid10("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
217468
218246
  const meta3 = { ...input2.purpose ? { purpose: input2.purpose } : {}, ...input2.quality ? { quality: input2.quality } : {} };
217469
218247
  if (!mediaDir) {
217470
218248
  const bytes = await readReviewFile(path, REVIEW_MEDIA_BYTES), sha2562 = createHash25("sha256").update(bytes).digest("hex");
217471
- if (input2.sha256 && input2.sha256 !== sha2562) invalid9("Preview hash does not match this version.");
218249
+ if (input2.sha256 && input2.sha256 !== sha2562) invalid10("Preview hash does not match this version.");
217472
218250
  return { uri: `data:${mime2[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime2[extension], ...meta3 };
217473
218251
  }
217474
218252
  const temporary = await productionOutputPath(root, `${mediaDir}/copy-${randomUUID10()}`);
217475
218253
  await mkdir18(dirname24(temporary), { recursive: true });
217476
218254
  try {
217477
218255
  const { sha256: sha2562, bytes } = await copyReviewFile(path, temporary);
217478
- if (input2.sha256 && input2.sha256 !== sha2562) invalid9("Preview hash does not match this version.");
217479
- const name = `${sha2562}${extension}`, file2 = `${mediaDir}/${name}`, uri = `${encodeURIComponent(basename5(mediaDir))}/${name}`;
218256
+ if (input2.sha256 && input2.sha256 !== sha2562) invalid10("Preview hash does not match this version.");
218257
+ const name = `${sha2562}${extension}`, file2 = `${mediaDir}/${name}`, uri = `${encodeURIComponent(basename6(mediaDir))}/${name}`;
217480
218258
  if (!entries.some((entry) => entry.uri === uri)) {
217481
218259
  await link7(temporary, await productionOutputPath(root, file2));
217482
218260
  entries.push({ uri, file: file2, sha256: sha2562, bytes, mimeType: mime2[extension] });
@@ -217488,9 +218266,9 @@ async function prepareMedia(root, input2, kind2, mediaDir, entries) {
217488
218266
  }
217489
218267
  }
217490
218268
  async function createReviewArtifact(root, value, out, mediaMode = "local") {
217491
- if (!["local", "embedded"].includes(mediaMode)) invalid9("Use --media-mode local or embedded.");
218269
+ if (!["local", "embedded"].includes(mediaMode)) invalid10("Use --media-mode local or embedded.");
217492
218270
  const input2 = parseReviewArtifact(value);
217493
- if (!out.endsWith(".html")) invalid9("Output must be a new .html file.");
218271
+ if (!out.endsWith(".html")) invalid10("Output must be a new .html file.");
217494
218272
  const target = await productionOutputPath(root, out);
217495
218273
  for (const path of [target, `${target}.review.json`]) {
217496
218274
  try {
@@ -217499,7 +218277,7 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
217499
218277
  if (error62.code === "ENOENT") continue;
217500
218278
  throw error62;
217501
218279
  }
217502
- invalid9("Review output already exists. Use a new filename; previous decisions are preserved.");
218280
+ invalid10("Review output already exists. Use a new filename; previous decisions are preserved.");
217503
218281
  }
217504
218282
  const entries = [];
217505
218283
  const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID10()}` : void 0;
@@ -217509,12 +218287,12 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
217509
218287
  directions.push({ ...direction, ...preview ? { preview: await prepareMedia(root, preview, "preview", mediaDir, entries) } : {} });
217510
218288
  }
217511
218289
  const clean = { schemaVersion: 1, projectId: input2.projectId, title: input2.title, version: input2.version, stage: input2.stage, ...input2.contextVersion ? { contextVersion: input2.contextVersion } : {}, ...video ? { video } : {}, ...directions ? { directions } : {}, ...input2.transcript ? { transcript: input2.transcript } : {}, ...input2.learnings ? { learnings: input2.learnings } : {}, ...input2.learningContext ? { learningContext: input2.learningContext } : {} };
217512
- if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid9("Embedded previews exceed 40 MiB. Use smaller review copies.");
218290
+ if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid10("Embedded previews exceed 40 MiB. Use smaller review copies.");
217513
218291
  const artifactId = createHash25("sha256").update(JSON.stringify(clean)).digest("hex");
217514
218292
  const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
217515
218293
  await mkdir18(dirname24(target), { recursive: true });
217516
218294
  await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
217517
- if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, html: { file: out, sha256: createHash25("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
218295
+ if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, projectId: input2.projectId, stage: input2.stage, ...input2.contextVersion ? { contextVersion: input2.contextVersion } : {}, ...directions ? { directionIds: directions.map((direction) => direction.id), directionPreviews: Object.fromEntries(directions.filter((direction) => direction.preview).map((direction) => [direction.id, direction.preview.sha256])) } : {}, presented: false, html: { file: out, sha256: createHash25("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
217518
218296
  return { kind: "editorbrain.review-artifact", path: target, artifactId, projectId: input2.projectId, stage: input2.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." };
217519
218297
  }
217520
218298
 
@@ -217522,18 +218300,18 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
217522
218300
  import { createServer as createServer3 } from "node:http";
217523
218301
  import { Readable } from "node:stream";
217524
218302
  import { createHash as createHash26, randomBytes as randomBytes2 } from "node:crypto";
217525
- import { basename as basename6 } from "node:path";
217526
- var hash9 = (bytes) => createHash26("sha256").update(bytes).digest("hex");
217527
- var invalid10 = () => 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.");
218303
+ import { basename as basename7 } from "node:path";
218304
+ var hash11 = (bytes) => createHash26("sha256").update(bytes).digest("hex");
218305
+ var invalid11 = () => 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.");
217528
218306
  var validHash = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
217529
218307
  async function startReviewArtifact(root, file2, port = 0) {
217530
218308
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError("INVALID_ARGUMENT", "Preview port must be 0 through 65535.", "Omit --port for an available loopback port.");
217531
- if (!file2.endsWith(".html")) throw invalid10();
218309
+ if (!file2.endsWith(".html")) throw invalid11();
217532
218310
  const manifestPath = await productionOutputPath(root, `${file2}.review.json`);
217533
218311
  const manifest = JSON.parse((await readReviewFile(manifestPath, 64 * 1024)).toString());
217534
- if (manifest?.schemaVersion !== 1 || manifest.kind !== "editorbrain.local-review" || !validHash(manifest.artifactId) || manifest.html?.file !== file2 || !validHash(manifest.html.sha256) || !Array.isArray(manifest.media) || manifest.media.length > 3) throw invalid10();
218312
+ if (manifest?.schemaVersion !== 1 || manifest.kind !== "editorbrain.local-review" || !validHash(manifest.artifactId) || manifest.html?.file !== file2 || !validHash(manifest.html.sha256) || !Array.isArray(manifest.media) || manifest.media.length > 3) throw invalid11();
217535
218313
  const html = await readReviewFile(await productionOutputPath(root, file2), 2 * 1024 * 1024);
217536
- if (hash9(html) !== manifest.html.sha256 || html.length !== manifest.html.bytes) throw invalid10();
218314
+ if (hash11(html) !== manifest.html.sha256 || html.length !== manifest.html.bytes) throw invalid11();
217537
218315
  const snapshots2 = [];
217538
218316
  const cleanup = async () => {
217539
218317
  await Promise.allSettled(snapshots2.splice(0).map((s) => s.close()));
@@ -217543,15 +218321,15 @@ async function startReviewArtifact(root, file2, port = 0) {
217543
218321
  try {
217544
218322
  const mime2 = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
217545
218323
  for (const entry of manifest.media) {
217546
- if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${file2}.media-`) || !validHash(entry.sha256)) throw invalid10();
218324
+ if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${file2}.media-`) || !validHash(entry.sha256)) throw invalid11();
217547
218325
  const suffix = entry.file.slice(`${file2}.media-`.length);
217548
218326
  const match = /^([a-f0-9-]{36})\/([a-f0-9]{64})\.(mp4|webm|png|jpg|jpeg|webp)$/.exec(suffix);
217549
- if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime2[match[3]]) throw invalid10();
217550
- const uri = `${encodeURIComponent(basename6(file2) + ".media-" + match[1])}/${match[2]}.${match[3]}`;
217551
- if (entry.uri !== uri || resources.has(uri)) throw invalid10();
218327
+ if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime2[match[3]]) throw invalid11();
218328
+ const uri = `${encodeURIComponent(basename7(file2) + ".media-" + match[1])}/${match[2]}.${match[3]}`;
218329
+ if (entry.uri !== uri || resources.has(uri)) throw invalid11();
217552
218330
  const snapshot = await openReviewSnapshot(await productionOutputPath(root, entry.file));
217553
218331
  snapshots2.push(snapshot);
217554
- if (snapshot.bytes !== entry.bytes || snapshot.sha256 !== entry.sha256) throw invalid10();
218332
+ if (snapshot.bytes !== entry.bytes || snapshot.sha256 !== entry.sha256) throw invalid11();
217555
218333
  resources.set(uri, { snapshot, bytes: snapshot.bytes, mime: entry.mimeType });
217556
218334
  }
217557
218335
  const token = randomBytes2(24).toString("hex"), prefix = `/${token}/`;
@@ -217632,7 +218410,7 @@ async function startReviewArtifact(root, file2, port = 0) {
217632
218410
  const address = server.address();
217633
218411
  if (!address || typeof address === "string") {
217634
218412
  server.close();
217635
- throw invalid10();
218413
+ throw invalid11();
217636
218414
  }
217637
218415
  origin = `http://127.0.0.1:${address.port}`;
217638
218416
  const url3 = `${origin}${prefix}index.html`;
@@ -217648,7 +218426,7 @@ async function startReviewArtifact(root, file2, port = 0) {
217648
218426
  };
217649
218427
  try {
217650
218428
  const probe2 = await fetch(url3, { signal: AbortSignal.timeout(5e3) });
217651
- if (probe2.status !== 200 || hash9(Buffer.from(await probe2.arrayBuffer())) !== manifest.html.sha256) throw invalid10();
218429
+ if (probe2.status !== 200 || hash11(Buffer.from(await probe2.arrayBuffer())) !== manifest.html.sha256) throw invalid11();
217652
218430
  } catch (error62) {
217653
218431
  await close();
217654
218432
  throw error62;
@@ -217665,56 +218443,56 @@ async function serveReviewArtifact(root, file2, port = 0) {
217665
218443
  } catch (error62) {
217666
218444
  if (error62 instanceof CliError) throw error62;
217667
218445
  if (error62.code === "EADDRINUSE") throw new CliError("REVIEW_PORT_UNAVAILABLE", "That preview port is already in use.", "Omit --port for a free port, or select another port in the host preview runner. Do not stop an unrelated server.");
217668
- throw invalid10();
218446
+ throw invalid11();
217669
218447
  }
217670
218448
  }
217671
218449
 
217672
218450
  // packages/cli/src/production-review-client.ts
217673
218451
  var productionReviewCommands = ["reviews", "transcript", "sample", "approve", "change", "feedback", "resolve-feedback", "revoke-sample"];
217674
- var invalid11 = (message) => {
218452
+ var invalid12 = (message) => {
217675
218453
  throw new CliError("INVALID_ARGUMENT", message, "Read editorbrain help and references/production-continuity.md.");
217676
218454
  };
217677
- var uuid9 = (value, name) => {
217678
- 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)) invalid11(`${name} must be a revision or feedback UUID.`);
218455
+ var uuid10 = (value, name) => {
218456
+ 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)) invalid12(`${name} must be a revision or feedback UUID.`);
217679
218457
  return value;
217680
218458
  };
217681
- var hash10 = (value, name) => {
217682
- if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid11(`${name} must be an exact SHA-256 hash.`);
218459
+ var hash12 = (value, name) => {
218460
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid12(`${name} must be an exact SHA-256 hash.`);
217683
218461
  return value;
217684
218462
  };
217685
218463
  var text14 = (value, name, max, optional2 = false) => {
217686
218464
  if (optional2 && (value === void 0 || value === null)) return "";
217687
- if (typeof value !== "string" || value.length > max || !optional2 && !value.trim()) invalid11(`${name} must contain ${optional2 ? "0" : "1"}\u2013${max} characters.`);
218465
+ if (typeof value !== "string" || value.length > max || !optional2 && !value.trim()) invalid12(`${name} must contain ${optional2 ? "0" : "1"}\u2013${max} characters.`);
217688
218466
  return value.trim();
217689
218467
  };
217690
218468
  function reviewBody(value, command) {
217691
- const fields2 = command === "sample" ? ["assetId", "contextVersion", "title", "notes", "parentRevisionId", "revisionId", "transcript", "supersedeParent"] : ["resultRevisionId", "contextVersion", "resultNote", "preservedElements"];
217692
- if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !fields2.includes(key))) invalid11("Use only documented review fields; project and feedback IDs come from command flags, never the JSON body.");
218469
+ const fields3 = command === "sample" ? ["assetId", "contextVersion", "title", "notes", "parentRevisionId", "revisionId", "transcript", "supersedeParent"] : ["resultRevisionId", "contextVersion", "resultNote", "preservedElements"];
218470
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !fields3.includes(key))) invalid12("Use only documented review fields; project and feedback IDs come from command flags, never the JSON body.");
217693
218471
  const body = value;
217694
- hash10(body.contextVersion, "contextVersion");
218472
+ hash12(body.contextVersion, "contextVersion");
217695
218473
  if (command === "sample") {
217696
- if (body.supersedeParent !== void 0 && (typeof body.supersedeParent !== "boolean" || body.supersedeParent && !body.parentRevisionId)) invalid11("supersedeParent must be a boolean and requires parentRevisionId when true.");
218474
+ if (body.supersedeParent !== void 0 && (typeof body.supersedeParent !== "boolean" || body.supersedeParent && !body.parentRevisionId)) invalid12("supersedeParent must be a boolean and requires parentRevisionId when true.");
217697
218475
  if (body.transcript !== void 0) {
217698
218476
  try {
217699
218477
  body.transcript = parseReviewTranscript(body.transcript);
217700
218478
  } catch (e) {
217701
- invalid11(e.message);
218479
+ invalid12(e.message);
217702
218480
  }
217703
218481
  }
217704
- hash10(body.assetId, "assetId");
218482
+ hash12(body.assetId, "assetId");
217705
218483
  text14(body.title, "title", 120);
217706
218484
  text14(body.notes, "notes", 2e3, true);
217707
- for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0) uuid9(body[key], key);
218485
+ for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0) uuid10(body[key], key);
217708
218486
  } else {
217709
- uuid9(body.resultRevisionId, "resultRevisionId");
218487
+ uuid10(body.resultRevisionId, "resultRevisionId");
217710
218488
  text14(body.resultNote, "resultNote", 1500);
217711
218489
  text14(body.preservedElements, "preservedElements", 2e3);
217712
218490
  }
217713
- if (Buffer.byteLength(JSON.stringify(body)) > (command === "sample" ? REVIEW_SAMPLE_MAX_BYTES : 8192)) invalid11(command === "sample" ? "Review metadata exceeds the 64 KiB service limit." : "Review metadata exceeds the 8 KiB service limit.");
218491
+ if (Buffer.byteLength(JSON.stringify(body)) > (command === "sample" ? REVIEW_SAMPLE_MAX_BYTES : 8192)) invalid12(command === "sample" ? "Review metadata exceeds the 64 KiB service limit." : "Review metadata exceeds the 8 KiB service limit.");
217714
218492
  return body;
217715
218493
  }
217716
218494
  async function productionReviewCommand(client, root, command, flags) {
217717
- if (!productionReviewCommands.includes(command)) invalid11("Unknown production review command.");
218495
+ if (!productionReviewCommands.includes(command)) invalid12("Unknown production review command.");
217718
218496
  const required2 = (name) => {
217719
218497
  const value = flags[name];
217720
218498
  if (typeof value !== "string" || !value) throw new CliError("INVALID_ARGUMENT", `--${name} is required.`, "Read editorbrain help.");
@@ -217734,24 +218512,24 @@ async function productionReviewCommand(client, root, command, flags) {
217734
218512
  const projectId = required2("project");
217735
218513
  assertIdentifier(projectId);
217736
218514
  const base = `/v1/projects/${encodeURIComponent(projectId)}`;
217737
- const revision2 = () => encodeURIComponent(uuid9(required2("revision"), "--revision"));
217738
- const contextVersion = () => hash10(required2("context-version"), "--context-version");
217739
- const after = flags.after === void 0 ? void 0 : uuid9(required2("after"), "--after");
218515
+ const revision2 = () => encodeURIComponent(uuid10(required2("revision"), "--revision"));
218516
+ const contextVersion = () => hash12(required2("context-version"), "--context-version");
218517
+ const after = flags.after === void 0 ? void 0 : uuid10(required2("after"), "--after");
217740
218518
  if (command === "transcript") return client.request(`${base}/production-reviews/${revision2()}/transcript`);
217741
218519
  if (command === "reviews") return client.request(`${base}/production-reviews${after ? "?" + new URLSearchParams({ after }) : ""}`);
217742
218520
  if (command === "feedback") {
217743
218521
  const query = new URLSearchParams();
217744
218522
  if (flags.status !== void 0) {
217745
218523
  const status = required2("status");
217746
- if (!["pending", "resolved"].includes(status)) invalid11("--status must be pending or resolved.");
218524
+ if (!["pending", "resolved"].includes(status)) invalid12("--status must be pending or resolved.");
217747
218525
  query.set("status", status);
217748
218526
  }
217749
- if (flags.revision !== void 0) query.set("revisionId", uuid9(required2("revision"), "--revision"));
218527
+ if (flags.revision !== void 0) query.set("revisionId", uuid10(required2("revision"), "--revision"));
217750
218528
  if (after) query.set("after", after);
217751
218529
  return client.request(`${base}/production-feedback?${query}`);
217752
218530
  }
217753
218531
  if (command === "sample" || command === "resolve-feedback") {
217754
- const feedbackId = command === "resolve-feedback" ? uuid9(required2("id"), "--id") : void 0;
218532
+ const feedbackId = command === "resolve-feedback" ? uuid10(required2("id"), "--id") : void 0;
217755
218533
  const body = reviewBody(await readProductionJson(root, required2("file")), command);
217756
218534
  return client.request(command === "sample" ? `${base}/production-reviews` : `${base}/production-feedback/${encodeURIComponent(feedbackId)}/resolve`, { method: "POST", body });
217757
218535
  }
@@ -217762,10 +218540,10 @@ async function productionReviewCommand(client, root, command, flags) {
217762
218540
  if (command === "revoke-sample") return client.request(`${base}/production-reviews/${revision2()}`, { method: "DELETE" });
217763
218541
  if (command === "change") {
217764
218542
  const segment = flags.segment === void 0 ? void 0 : required2("segment");
217765
- if (segment !== void 0 && !/^[a-zA-Z0-9_-]{1,80}$/.test(segment)) invalid11("Use a valid transcript segment ID.");
218543
+ if (segment !== void 0 && !/^[a-zA-Z0-9_-]{1,80}$/.test(segment)) invalid12("Use a valid transcript segment ID.");
217766
218544
  const times = flags.at === void 0 ? [] : required2("at").split(",");
217767
218545
  if (times.length > 2 || times.some((t) => !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(t) || !Number.isFinite(Number(t)) || Number(t) > 36e3) || times.length === 2 && Number(times[1]) < Number(times[0])) throw new CliError("INVALID_ARGUMENT", "--at accepts one second or a start,end range between 0 and 36000 seconds.", "Example: --at 12,15.5. Omit it for the whole sample.");
217768
- return client.request(`${base}/production-reviews/${revision2()}/changes`, { method: "POST", body: { contextVersion: contextVersion(), text: text14(required2("text"), "--text", 1500), target: { ...segment ? { segmentId: segment } : {}, ...times.length ? { startMs: Math.round(Number(times[0]) * 1e3), ...times.length === 2 ? { endMs: Math.round(Number(times[1]) * 1e3) } : {} } : {} }, ...flags.id !== void 0 ? { feedbackId: uuid9(required2("id"), "--id") } : {} } });
218546
+ return client.request(`${base}/production-reviews/${revision2()}/changes`, { method: "POST", body: { contextVersion: contextVersion(), text: text14(required2("text"), "--text", 1500), target: { ...segment ? { segmentId: segment } : {}, ...times.length ? { startMs: Math.round(Number(times[0]) * 1e3), ...times.length === 2 ? { endMs: Math.round(Number(times[1]) * 1e3) } : {} } : {} }, ...flags.id !== void 0 ? { feedbackId: uuid10(required2("id"), "--id") } : {} } });
217769
218547
  }
217770
218548
  throw new CliError("INVALID_ARGUMENT", "Unknown production review command.", "Read editorbrain help.");
217771
218549
  }
@@ -217774,7 +218552,7 @@ async function productionReviewCommand(client, root, command, flags) {
217774
218552
  import { constants as constants17 } from "node:fs";
217775
218553
  import { open as open22, mkdir as mkdir19 } from "node:fs/promises";
217776
218554
  import { randomUUID as randomUUID11 } from "node:crypto";
217777
- import { basename as basename7, extname as extname9, join as join23 } from "node:path";
218555
+ import { basename as basename8, extname as extname10, join as join23 } from "node:path";
217778
218556
 
217779
218557
  // packages/cli/src/production-parent.ts
217780
218558
  var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
@@ -217816,7 +218594,7 @@ async function latestProductionParent(client, projectId) {
217816
218594
  var HASH2 = /^[a-f0-9]{64}$/;
217817
218595
  var UUID2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
217818
218596
  var MAX_BYTES2 = 90 * 1024 * 1024;
217819
- var invalid12 = (message) => {
218597
+ var invalid13 = (message) => {
217820
218598
  throw new CliError("INVALID_ARGUMENT", message, "Use production submit --project ID --file relative.mp4 --title TEXT [--parent UUID|latest] [--notes TEXT] [--quality 480|720].");
217821
218599
  };
217822
218600
  async function optionalText2(root, path, document2 = true) {
@@ -217841,14 +218619,14 @@ async function verifyRegistered(value, receipt) {
217841
218619
  if (!JSON.parse(value.media.content).assets.some((asset) => asset.id === receipt.preview.sha256)) throw new CliError("SUBMISSION_RESPONSE_INVALID", "The returned media document does not reference this submitted preview.", "Keep the receipt and inspect the registered submission before reconciling media.");
217842
218620
  }
217843
218621
  async function submitProduction(client, root, flags, runtime2 = { probe: probeLocalMedia, prepare: prepareMediaPreview }) {
217844
- for (const key of Object.keys(flags)) if (!["project", "file", "title", "parent", "notes", "quality", "dir", "url"].includes(key)) invalid12(`--${key} is not supported for production submit.`);
217845
- const required2 = (key) => typeof flags[key] === "string" && flags[key].trim() ? flags[key] : invalid12(`--${key} is required.`);
218622
+ for (const key of Object.keys(flags)) if (!["project", "file", "title", "parent", "notes", "quality", "dir", "url"].includes(key)) invalid13(`--${key} is not supported for production submit.`);
218623
+ const required2 = (key) => typeof flags[key] === "string" && flags[key].trim() ? flags[key] : invalid13(`--${key} is required.`);
217846
218624
  const projectId = assertIdentifier(required2("project")), file2 = required2("file"), title = required2("title").trim();
217847
218625
  const notes = flags.notes === void 0 ? void 0 : required2("notes").trim(), parentRevisionId = flags.parent === void 0 ? void 0 : required2("parent");
217848
- if (title.length > 120 || notes !== void 0 && notes.length > 2e3 || parentRevisionId !== void 0 && parentRevisionId !== "latest" && !UUID2.test(parentRevisionId)) invalid12("Use a title up to 120 characters, notes up to 2000, and a parent UUID or latest.");
218626
+ if (title.length > 120 || notes !== void 0 && notes.length > 2e3 || parentRevisionId !== void 0 && parentRevisionId !== "latest" && !UUID2.test(parentRevisionId)) invalid13("Use a title up to 120 characters, notes up to 2000, and a parent UUID or latest.");
217849
218627
  const selectedQuality = flags.quality === void 0 ? 720 : Number(required2("quality"));
217850
- const quality = selectedQuality === 480 ? 480 : selectedQuality === 720 ? 720 : invalid12("--quality must be 480 or 720.");
217851
- if (extname9(file2).toLowerCase() !== ".mp4") invalid12("--file must name a workspace-relative MP4.");
218628
+ const quality = selectedQuality === 480 ? 480 : selectedQuality === 720 ? 720 : invalid13("--quality must be 480 or 720.");
218629
+ if (extname10(file2).toLowerCase() !== ".mp4") invalid13("--file must name a workspace-relative MP4.");
217852
218630
  const sourcePath = await checkedPath(root, file2, false), source2 = await runtime2.probe(sourcePath);
217853
218631
  const me = await client.me();
217854
218632
  await loadSyncState(root, client.url, me.workspaceId);
@@ -217933,7 +218711,7 @@ async function submitProduction(client, root, flags, runtime2 = { probe: probeLo
217933
218711
  if (await sha256(bytes) !== receipt.preview.sha256) throw new CliError("SUBMISSION_PREVIEW_CHANGED", "The preview changed during upload preparation.", "Restore its exact bytes before retrying.");
217934
218712
  receipt.state = "uploading";
217935
218713
  await save(receipt);
217936
- const params = new URLSearchParams({ name: basename7(file2, extname9(file2)) + "-review.mp4", projectId, purpose: "preview", ...receipt.sourceSha256 !== receipt.preview.sha256 ? { sourceSha256: receipt.sourceSha256 } : {} });
218714
+ const params = new URLSearchParams({ name: basename8(file2, extname10(file2)) + "-review.mp4", projectId, purpose: "preview", ...receipt.sourceSha256 !== receipt.preview.sha256 ? { sourceSha256: receipt.sourceSha256 } : {} });
217937
218715
  const uploaded = await client.uploadPreview(`/v1/assets/${receipt.preview.sha256}?${params}`, bytes, "video/mp4");
217938
218716
  const asset = await uploaded.json();
217939
218717
  if (asset.id !== receipt.preview.sha256 || asset.sha256 !== receipt.preview.sha256 || asset.bytes !== bytes.byteLength || asset.mimeType !== "video/mp4") throw new CliError("SUBMISSION_UPLOAD_UNCONFIRMED", "The preview upload response could not be verified.", "Retry the same submission; its hash preflight will inspect the existing bytes before any upload.");
@@ -218140,6 +218918,8 @@ editorbrain production matte-plan --file montage.mp4 [--dir folder]
218140
218918
  editorbrain production check --file render [--profile local-profile.json] [--dir folder] [--out .editorbrain-local/report.json] [--details]
218141
218919
  editorbrain production verify --project ID --file final.mp4 [--ocr] [--ocr-language eng] [--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]
218142
218920
  editorbrain production review-artifact --file review.json --out .editorbrain-local/review-v1.html [--media-mode local|embedded] [--dir folder]
218921
+ editorbrain production present --project ID [--file presentation.json | --id UUID] [--dir folder] [--url https://server]
218922
+ editorbrain production withdraw --project ID --id UUID --expected-version HASH --user-confirmed [--url https://server]
218143
218923
  editorbrain production review-open --file .editorbrain-local/review-v1.html [--port 0] [--dir folder]
218144
218924
  editorbrain production reviews --project ID [--after UUID]
218145
218925
  editorbrain production transcript --project ID --revision UUID
@@ -218683,6 +219463,27 @@ async function main() {
218683
219463
  }
218684
219464
  return;
218685
219465
  }
219466
+ if (command === "production" && subcommand === "withdraw") {
219467
+ if (argument || Object.keys(args.flags).some((key) => !["project", "id", "expected-version", "user-confirmed", "url"].includes(key))) throw new CliError("INVALID_ARGUMENT", "Unsupported production withdraw option.", "Read production withdraw --help.");
219468
+ output2(await withdrawPresentation(new Client(await config2(args)), str(args, "project") ?? "", str(args, "id") ?? "", str(args, "expected-version") ?? "", args.flags["user-confirmed"] === true));
219469
+ return;
219470
+ }
219471
+ if (command === "production" && subcommand === "present") {
219472
+ if (argument || Object.keys(args.flags).some((key) => !["project", "file", "id", "dir", "url"].includes(key))) throw new CliError("INVALID_ARGUMENT", "Unsupported production present option.", "Use --project ID; omit --file to read current evidence/version, or --id UUID for an exact historical receipt. Supply --file only after sharing the artifact with the user.");
219473
+ const projectId = str(args, "project");
219474
+ if (!projectId) throw new CliError("INVALID_ARGUMENT", "--project is required.", "Use production present --project ID.");
219475
+ assertIdentifier(projectId);
219476
+ const receiptId = str(args, "id"), file2 = str(args, "file");
219477
+ if (receiptId && (file2 || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(receiptId))) throw new CliError("INVALID_ARGUMENT", "Use --id UUID for reading one receipt, or --file to record a presentation.", "Keep the same evidenceId when recovering an uncertain write.");
219478
+ const client = new Client(await config2(args));
219479
+ if (!file2) {
219480
+ output2(await client.request(`/v1/projects/${encodeURIComponent(projectId)}/review-evidence${receiptId ? "/" + receiptId : ""}`));
219481
+ return;
219482
+ }
219483
+ const root2 = await ensureRoot(str(args, "dir") ?? process.cwd());
219484
+ output2(await presentProduction(client, root2, projectId, await readPresentationInput(root2, file2)));
219485
+ return;
219486
+ }
218686
219487
  if (command === "production" && subcommand === "review-artifact") {
218687
219488
  if (argument || Object.keys(args.flags).some((k) => !["file", "out", "dir", "media-mode"].includes(k))) throw new CliError("INVALID_ARGUMENT", "Unsupported review-artifact option.", "Use --file, --out, optional --media-mode local|embedded and --dir.");
218688
219489
  const root2 = resolve19(str(args, "dir") ?? process.cwd()), file2 = str(args, "file"), out = str(args, "out");
@@ -219221,17 +220022,17 @@ async function main() {
219221
220022
  await handle.close();
219222
220023
  }
219223
220024
  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" };
219224
- const mimeType = str(args, "mime") ?? types2[extname10(target).toLowerCase()];
220025
+ const mimeType = str(args, "mime") ?? types2[extname11(target).toLowerCase()];
219225
220026
  if (!mimeType) throw new Error("Unsupported extension; specify --mime for a supported media format");
219226
- const hash11 = await sha256(bytes);
219227
- const params = new URLSearchParams({ name: basename8(target) });
220027
+ const hash13 = await sha256(bytes);
220028
+ const params = new URLSearchParams({ name: basename9(target) });
219228
220029
  if (str(args, "project")) params.set("projectId", str(args, "project"));
219229
220030
  if (str(args, "purpose")) params.set("purpose", str(args, "purpose"));
219230
220031
  if (str(args, "source-sha256")) params.set("sourceSha256", str(args, "source-sha256"));
219231
- const path = `/v1/assets/${hash11}?${params}`;
220032
+ const path = `/v1/assets/${hash13}?${params}`;
219232
220033
  const result2 = str(args, "purpose") === "preview" ? await client.uploadPreview(path, bytes, mimeType) : await client.media(path, { content: bytes, mimeType });
219233
220034
  const body = await result2.json();
219234
- if (body.sha256 !== hash11) throw new Error("Upload response hash mismatch");
220035
+ if (body.sha256 !== hash13) throw new Error("Upload response hash mismatch");
219235
220036
  output2(body);
219236
220037
  return;
219237
220038
  }
@@ -219239,11 +220040,11 @@ async function main() {
219239
220040
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
219240
220041
  const destination = resolve19(str(args, "dir") ?? process.cwd(), str(args, "out"));
219241
220042
  const root2 = await ensureRoot(dirname25(destination), true);
219242
- await checkedPath(root2, basename8(destination), false);
220043
+ await checkedPath(root2, basename9(destination), false);
219243
220044
  const response = await client.media(`/v1/assets/${argument}`);
219244
220045
  const bytes = new Uint8Array(await response.arrayBuffer());
219245
220046
  if (await sha256(bytes) !== argument) throw new Error("Downloaded asset failed SHA-256 verification");
219246
- await atomicWrite(root2, basename8(destination), bytes, { document: false, overwrite: false });
220047
+ await atomicWrite(root2, basename9(destination), bytes, { document: false, overwrite: false });
219247
220048
  output2({ path: destination, sha256: argument, bytes: bytes.length });
219248
220049
  return;
219249
220050
  }
@@ -219305,7 +220106,10 @@ async function main() {
219305
220106
  previousContextVersion: str(args, "previous-context-version"),
219306
220107
  ...str(args, "questions") ? { questionNeeds: await readProductionJson(await ensureRoot(str(args, "dir") ?? process.cwd()), str(args, "questions")) } : {}
219307
220108
  } });
219308
- output2(args.flags.summary && result2?.kind !== "editorbrain.workflow-summary" ? summarizeWorkflow(result2) : result2);
220109
+ const projectId = str(args, "project");
220110
+ const localSync = projectId ? await projectLocalSync(client, await ensureRoot(str(args, "dir") ?? process.cwd()), projectId, result2.editorialSnapshot?.sourceHashes) : void 0;
220111
+ const projected = args.flags.summary && result2.kind !== "editorbrain.workflow-summary" ? summarizeWorkflow(result2) : result2;
220112
+ output2({ ...projected, ...localSync ? { localSync } : {} });
219309
220113
  return;
219310
220114
  }
219311
220115
  if (command === "search" && subcommand === "brief") {
@@ -219353,10 +220157,10 @@ async function main() {
219353
220157
  if (assetId && !/^[a-f0-9]{64}$/.test(assetId)) throw new Error("--asset requires an owned production asset SHA-256.");
219354
220158
  if (videoPath) {
219355
220159
  const bytes = await readInput(videoPath, 12 * 1024 * 1024);
219356
- const mimeType = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" }[extname10(videoPath).toLowerCase()];
220160
+ const mimeType = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" }[extname11(videoPath).toLowerCase()];
219357
220161
  if (!mimeType) throw new Error("Use MP4, MOV or WebM.");
219358
220162
  assetId = await sha256(bytes);
219359
- const uploaded = await client.media(`/v1/assets/${assetId}?name=${encodeURIComponent(basename8(videoPath))}`, { content: bytes, mimeType });
220163
+ const uploaded = await client.media(`/v1/assets/${assetId}?name=${encodeURIComponent(basename9(videoPath))}`, { content: bytes, mimeType });
219360
220164
  if ((await uploaded.json()).sha256 !== assetId) throw new Error("Upload hash mismatch.");
219361
220165
  }
219362
220166
  if (!script && !assetId && !str(args, "project")) throw new Error("Provide --script, --video, --asset or --project with a saved script.");
@@ -219389,20 +220193,20 @@ async function main() {
219389
220193
  }
219390
220194
  if (subcommand === "get" && argument) {
219391
220195
  const document2 = str(args, "document");
219392
- const hash11 = str(args, "sha256");
219393
- if (hash11 && !document2) throw new Error("--sha256 requires --document for library get.");
219394
- const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash11 ? { sha256: hash11 } : {} })}` : ""}`);
219395
- if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash11 && result2.sha256 !== hash11)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
220196
+ const hash13 = str(args, "sha256");
220197
+ if (hash13 && !document2) throw new Error("--sha256 requires --document for library get.");
220198
+ const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash13 ? { sha256: hash13 } : {} })}` : ""}`);
220199
+ if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash13 && result2.sha256 !== hash13)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
219396
220200
  output2(result2);
219397
220201
  return;
219398
220202
  }
219399
220203
  if (subcommand === "media" && argument && str(args, "out")) {
219400
- const hash11 = str(args, "sha256");
219401
- if (!hash11 || !/^[a-f0-9]{64}$/.test(hash11)) throw new Error("--sha256 must be a media SHA-256 from library get.");
220204
+ const hash13 = str(args, "sha256");
220205
+ if (!hash13 || !/^[a-f0-9]{64}$/.test(hash13)) throw new Error("--sha256 must be a media SHA-256 from library get.");
219402
220206
  const destination = resolve19(str(args, "dir") ?? process.cwd(), str(args, "out"));
219403
220207
  const root2 = await ensureRoot(dirname25(destination), true);
219404
- await checkedPath(root2, basename8(destination), false);
219405
- const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash11}`);
220208
+ await checkedPath(root2, basename9(destination), false);
220209
+ const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash13}`);
219406
220210
  const reader = response.body?.getReader();
219407
220211
  if (!reader) throw new Error("Media body missing.");
219408
220212
  const chunks = [];
@@ -219418,9 +220222,9 @@ async function main() {
219418
220222
  chunks.push(value);
219419
220223
  }
219420
220224
  const bytes = Buffer.concat(chunks);
219421
- if (await sha256(bytes) !== hash11) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
219422
- await atomicWrite(root2, basename8(destination), bytes, { document: false, overwrite: false });
219423
- output2({ videoId: argument, path: destination, sha256: hash11, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
220225
+ if (await sha256(bytes) !== hash13) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
220226
+ await atomicWrite(root2, basename9(destination), bytes, { document: false, overwrite: false });
220227
+ output2({ videoId: argument, path: destination, sha256: hash13, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
219424
220228
  return;
219425
220229
  }
219426
220230
  throw new Error("Use library search, library get, or library media <video-id> --sha256 hash --out file.");